React是一个流行的JavaScript库,用于构建用户界面。React可用于构建单页面应用程序、移动应用程序和桌面应用程序等。它采用了组件化的开发方式,使得代码易于维护、重复使用和升级。以下是React的基础知识。
- JSX
React使用JSX语法来描述UI组件。JSX可以将HTML标记和JavaScript代码混合在一起,使得编写UI组件更加方便。例如:
const element = <h1>Hello, world!</h1>;
在上面的代码中,<h1>标记表示头部标记,而Hello, world!是JavaScript字符串。这个表达式将返回一个React元素,它可以被渲染到页面上。
- 组件
React的核心思想是组件化。组件是由多个不同的组成部分构成的,每个组成部分都有自己的状态和行为。组件可以嵌套在其他组件中,形成一个完整的UI界面。下面是一个简单的React组件:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
ReactDOM.render(
<Welcome name="Alice" />,
document.getElementById('root')
);
在上面的代码中,Welcome类是一个React组件,它接受一个name属性作为参数,并在render()方法中返回一个<h1>标记。ReactDOM.render()方法将组件渲染到页面上。
- 状态
状态是组件中的数据。当组件的状态发生变化时,React会自动重新渲染组件,并更新UI界面。例如:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: 0};
}
handleClick() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.handleClick()}>Increment</button>
</div>
);
}
}
ReactDOM.render(
<Counter />,
document.getElementById('root')
);
在上面的代码中,Counter类是一个计数器组件,它有一个count状态,并且在点击按钮时增加计数器的值。handleClick()方法使用setState()方法来更新组件的状态,从而触发重新渲染。<p>标记显示计数器的当前值,而<button>标记用于触发点击事件。
- 生命周期
React组件具有生命周期,在特定时刻调用生命周期方法可以执行一些操作,例如组件挂载、卸载和更新等。下面是一些常用的生命周期方法:
componentDidMount():组件已经被渲染到页面上后调用。componentWillUnmount():组件将要被从页面上卸载前调用。componentDidUpdate(prevProps, prevState):组件已经更新后调用,可以比较前后状态判断是否需要重新渲染组件。
例如:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({date: new Date()});
}
render() {
return <p>Current time is {this.state.date.toLocaleTimeString()}.</p>;
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
在上面的代码中,Clock类是一个显示当前时间的组件。在componentDidMount()方法中启动定时器,每秒钟调用一次tick()方法更新组件的状态,并使用toLocaleTimeString()方法格式化显示时间。
以上是React的基础知识。