https://codesandbox.io/s/nift... 沙箱
为什么使用{props.children}父组件更改状态子组件不会触发render?
const ComA = () => {
console.log("ComA render");
return <div>ComA</div>;
};
const ComB = () => {
console.log("ComB render");
return <div>ComB</div>;
};
function App(props) {
console.log("App render");
const [text, setText] = useState("text");
return (
<div className="App">
<ComA />
<ComB />
<button onClick={setText.bind(null, "update_text"+Math.random())}>
updateText({text})
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
打印:
App render
ComA render
ComB render
const ComA = () => {
console.log("ComA render");
return <div>ComA</div>;
};
const ComB = () => {
console.log("ComB render");
return <div>ComB</div>;
};
function App(props) {
console.log("App render");
const [text, setText] = useState("text");
return (
<div className="App">
{props.children}
<button onClick={setText.bind(null, "update_text" + Math.random())}>
updateText({text})
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<App>
<ComA />
<ComB />
</App>,
rootElement
);
打印:
App render