ReactJS
ReactJS
Built-in components:
div, a, p, img,…
As expressions:
<a className={className} href={targetUrl}>
{title}</a>
return <div>{list}</div>;
}
function MyComponent() {
return <h1 style={myStyle}>Head</h1>
}
function MyComponent() {
return <h1 className="header">Head</h1>
}
function App() {
return <Layout
header={<h1>Title</h1>}
footer={<div>Footer</div>}
>
<p>Hello</p>
<p>Content</p>
</Layout>
}
this.state = {
name: "John Doe",
age: 20
}
}
render() {
return <div>
{`${this.state.name} is ${this.state.age} years old`}
</div>;
}
}
function Person() {
const [name, setName] = useState("John Doe");
const [age, setAge] = useState(20);
render() {
return <button onClick={this.handleClick}>
Hello
</button>
}
}
handleClick() {
this.setState({ clicked: true }); // Error
}
render() {
return <button onClick={this.handleClick}>
Hello</button>
}
}
20 AC3040: Mobile Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Method 1
class MyButton extends Component {
constructor(props) {
super(props)
this.state = { clicked: false }
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({ clicked: true }); // Fine
}
render() {
return <button onClick={this.handleClick}>
Hello</button>
}
}
handleClick() {
this.setState({ clicked: true }); // Fine
}
render() {
return <button onClick=
{this.handleClick.bind(this)}>
Hello</button>
}
}
handleClick() {
this.setState({ clicked: true }); // Fine
}
render() {
return <button onClick=
{() => this.handleClick()}>
Hello</button>
}
}
Methods 2, 3 create a new function each time the component renders, which
may have performance implications ➔ Method 1 is preferred
23 AC3040: Mobile Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Passing Parameters to an Event Handler
Sometimes, we want to pass an extra parameter to an
event handler
<button onClick={this.deleteRow.bind(this,
id)}>Delete Row</button>
function IntPicker() {
const [value, setValue] = useState(10);
return <>
<MyValue text={value} />
<MyButton title="+"
handler={() => setValue(value + 1)} />
<MyButton title="-"
handler={() => setValue(value - 1)} />
</>
}