简体   繁体   中英

react: How to change the state of a child component(function component, not class component) from its parent?

I can change the state of child component which is class componet by ref ,but how can I change the function child compment ?

you will need to pass the parent state in to child component as prop.

childComponent

export function ChildComponent(props) {

   return(
      <div> <p>You have clicked it {props.count} Times</p></div>
  )
}

parentComponent

import {ChildComponent} from './child.js'
function ParentComponent() {
 const [count, setCount] = useState(0);
return (
    <div>
        <ChildComponent count={count}/>
         <button onClick={() => setCount(count + 1)}>
    </div>
)
}

Here is an example using forwardRef() and storing the child's state handler function in the passed ref which can then be called from the parent.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM