gpt4 book ai didi

javascript - 在 React 中将子组件中函数中存储的值传递给父组件

转载 作者:行者123 更新时间:2023-11-28 03:21:47 24 4
gpt4 key购买 nike

下面是我的代码。

子组件

  const onSave = () => {
var val = value
props.onSave();
}

<div onClick={() => { onSave() }}>
<CheckButton variant="contained" text-align='center' />
</div>

父组件

export const Card = (props) => {
const onSave = (val) => { [I WANT TO ACCESS val within here] }
}


<TextInputContainer onSave={() => onSave()} />

有什么方法可以访问父组件内的变量 val 吗?代码被大幅 chop 。实际代码使用Redux。

最佳答案

react的createRef帮助你访问react组件的值:

引用 ( https://pt-br.reactjs.org/docs/hooks-reference.html )

constructor () {this.CheckButtonRef = createRef()}
onSave = () => {props.onSave(this.CheckButtonRef.current.value)}
<CheckButton ref = {this.CheckButtonRef}/>

关于javascript - 在 React 中将子组件中函数中存储的值传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59094354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com