简体   繁体   中英

Change child component state in react

I'm new to react. I'm starting to think that I'm wrong but I used to think that you could make the same using Functional syntax or Class-Components syntax. Is there a way to change the state of a child component using Functional components?

I mean something like this...

_onChildClick = (key, childProps) => {
    this.setState({show: !this.state.show})
  }

Thank you in advance

You can do it like this:

 const {useState} = React; function App(){ const [count, setCount] = useState(0); return <div> Current count: {count}<br/> <button onClick={()=>setCount(count-1)}>-</button> <button onClick={()=>setCount(count+1)}>+</button> </div>; } ReactDOM.render(<App/>, document.querySelector('#app'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.5/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.5/umd/react-dom.production.min.js"></script> <div id='app'></div>

Hope this helps,

No, a parent component cannot change the state of a child component. The parent can only pass props to its children. This is the same for both functional and class-based components.

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