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值也會發生變化,從而觸發子組件重新渲染。