繁体   English   中英

在 React 的父组件中触发动作时获取子状态

[英]Get child state when the action is triggered in parent component in React

我想在父组件中单击按钮时获取子组件的状态。 子组件处理自己的状态。 但是当在父组件中触发操作时,我想要子组件的数据

最简单形式的代码片段,我无法更改组件架构

const Child = (props) => {
    const [name, setName] = useState("")
    return (
        <input value={name} onChange={(e) => { setName(e.target.value) }} />
    )
}

const parent = (props) => {
    const abc=()=>{
        // i want the name value here
    }
    return (
        <React.Fragment>
            <Child />
            <button onClick={()=>{abc()}}>Abc</button>
        </React.Fragment>
    )
}

与大多数问题一样,有多种方法可以解决这个问题。 对于不同的用例,每个解决方案都将更合适且更具可读性。

一种选择是将状态移动到父组件中。

const Child = (props) => {
    return (
        <input value={props.name} onChange={(e) => { props.setName(e.target.value) }} />
    )
}

const parent = (props) => {
    const [name, setName] = useState("")
    const abc=()=>{
        // i want the name value here
    }
    return (
        <React.Fragment>
            <Child name={name} setName={setName} />
            <button onClick={()=>{abc()}}>Abc</button>
        </React.Fragment>
    )
}

另一种方法是使用useRef 有关此用例的更多文档

const Child = (props) => {
    const [name, setName] = useState("")
    props.nameRef.current = name
    return (
        <input value={name} onChange={(e) => { setName(e.target.value) }} />
    )
}

const parent = (props) => {
    const nameRef = useRef("");
    const abc=()=>{
        // i want the name value here
    }
    return (
        <React.Fragment>
            <Child  nameRef={nameRef}/>
            <button onClick={()=>{abc()}} >Abc</button>
        </React.Fragment>
    )
}

恕我直言,大多数时候你应该使用第一个。 但是,如果它使代码在子组件中的状态更具可读性,或者重构会花费太多时间,那么第二个示例也能正常工作。

const Child = (props) => {

    return (
        <input value={name} onChange={e =>  setName(e.target.value) } />
    )
}

const parent = (props) => {
const [name, setName] = useState("")
    const abc=()=>{
        // i want the name value here
    }
    return (
        <React.Fragment>
            <Child setName={setName}/>
            <button onClick={()=>{abc()}}>Abc</button>
        </React.Fragment>
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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