从 Child 组件响应更改 UseState

React change UseState from Child Component

是否可以从 child 组件内部更改 useState 的值?

Parent:

const [state, setState] = useState(false);

return <Child func={() => setState(true)}/>

Child:

return <Button onClick={props.func}> Click me to set the state </Button>

这样不行,请问有什么办法吗? 谢谢

这应该可行,只要您还提供一种查看已更改状态值的方法:

const { useState } = React;
const App = () => {
  const [state, setState] = useState(false);
  return (
    <div>
      State: {String(state)}
      <Child func={() => setState(true)}/>
    </div>
  );
};
const Child = (props) => {
  return <button onClick={props.func}> Click me to set the state </button>;
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

你可以这样做

//PARENT
export default function Parent({}) {
  const [state, setState] = useState(false);
        function setParentValue(value){
             setState(value)
       }

        return <Child setValue={setParentValue} />

}

//CHILD
export default function Child({setValue}) {
  function buttonHandler(){
      setValue('value')
 }
  return <Button onClick={buttonHandler}> Click me to set the state </Button>

}


你的看起来不错。但是你有 <Button> 组件吗?如果不是,请将“b”小写并使用 html 的 <button>.

const Parent = () => {
  const [state, setState] = React.useState(false);
  
  const toggleState = () => setState(prevState => !prevState)
  
  return (
    <div>
      <p>Parent State: {String(state)}</p>
      <Child toggleState={toggleState}/>
    </div>
  );
};

const Child = ({toggleState}) => {
  return <button onClick={toggleState}>Child Button</button>;
};



ReactDOM.render(<Parent />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>