reactの子コンポーネントの再レンダリングの方法は何ですか?
Reactの中で、子コンポーネントを再レンダリングする方法は2つあります。
- 親コンポーネントが子コンポーネントにpropsを伝えると、propsが変更された時に子コンポーネントが再レンダリングされます。これはReactで最も一般的な方法であり、親コンポーネントのstateやpropsを使用して子コンポーネントのレンダリングを制御することができます。
たとえば、
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値が表示されます。
- ReactのContext APIを使用して、子コンポーネントの再レンダリングを実現します。Context APIはデータをコンポーネントツリー全体で共有できるため、Contextの値が変化すると影響を受ける子コンポーネントが再レンダリングされます。
例えば、
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も変化し、それにより子コンポーネントの再レンダリングが発生します。