![](/img/trans.png)
[英]React - parent class component function change class of child component
[英]react: How to change the state of a child component(function component, not class component) from its parent?
我可以通过ref
更改子组件的 state,即class componet
,但是如何更改function child compment
?
您需要将父 state 作为道具传递给子组件。
子组件
export function ChildComponent(props) {
return(
<div> <p>You have clicked it {props.count} Times</p></div>
)
}
父组件
import {ChildComponent} from './child.js'
function ParentComponent() {
const [count, setCount] = useState(0);
return (
<div>
<ChildComponent count={count}/>
<button onClick={() => setCount(count + 1)}>
</div>
)
}
这是一个使用forwardRef()
并将子级的 state 处理程序 function 存储在传递的ref
中的示例,然后可以从父级调用。
const App = () => { const childRef = React.useRef(); return ( <div> <Child ref={childRef} /> <button type="button" onClick={() => childRef.current()}>Toggle child</button> </div> ) } const Child = React.forwardRef((props, ref) => { const [red, setRed] = React.useState(false); const toggleRed = () => { setRed(p =>;p). } ref;current = toggleRed? return ( <div > <div className={`child ${red: 'red'; 'gray'}`}></div> </div> ). }) ReactDOM,render( <App />. document;getElementById("root") );
.child { height: 100px; width: 100px; }.red { background-color: tomato; }.gray { background-color: lightgray; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.