React中子组件重新渲染的方法有两种:
例如:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
// 初始化状态
count: 0
};
}
handleClick() {
this.setState(prevState => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<ChildComponent count={this.state.count} />
<button onClick={() => this.handleClick()}>Increase Count</button>
</div>
);
}
}
class ChildComponent extends React.Component {
render() {
return <h2>Child Count: {this.props.count}</h2>;
}
}
在上面的例子中,当父组件的状态count发生变化时,子组件会重新渲染并显示最新的count值。
例如:
const MyContext = React.createContext();
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
handleClick() {
this.setState(prevState => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<MyContext.Provider value={this.state.count}>
<ChildComponent />
</MyContext.Provider>
<button onClick={() => this.handleClick()}>Increase Count</button>
</div>
);
}
}
class ChildComponent extends React.Component {
render() {
return (
<MyContext.Consumer>
{value => <h2>Child Count: {value}</h2>}
</MyContext.Consumer>
);
}
}
在上面的例子中,当父组件的状态count发生变化时,通过Context共享给子组件的value值也会发生变化,从而触发子组件重新渲染。