简体   繁体   English

是否可以将 setState 方法作为道具传递?

[英]Is it possible to pass the setState method as props?

I want to pass the setState method to a functional component and access it from there.我想将 setState 方法传递给功能组件并从那里访问它。

On class component在 class 组件上

<InputRender name2={this.state.name2} setState={this.setState}/>

Functional component功能组件

import React from 'react';
export const InputRender=(props)=>{
return(
        <input
        type="text"
        onChange={(e) => { props.setState({ name2: e.target.value }); }}
        value={props.name2} />
    )
}

When trying to change the input while running I'm getting this error: TypeError: Cannot read property 'enqueueSetState' of undefined在运行时尝试更改输入时出现此错误: TypeError: Cannot read property 'enqueueSetState' of undefined

I know there can be many workarounds for this and I can implement them but I want to know if this achievable and if not then why.我知道可以有很多解决方法,我可以实现它们,但我想知道这是否可以实现,如果不能那么为什么。

You should bind the setState function.您应该绑定 setState function。

setState={this.setState.bind(this)}

Avoid using the name that exists in React by default, I would suggest to use some custom name:-避免使用默认存在于 React 中的名称,我建议使用一些自定义名称:-

Something similar to what you did but different format与您所做的类似,但格式不同

_updateName = (newName) => {
  this.setState({ name2: newName });
}

<InputRender name2={this.state.name2} updateName={this._updateName}/>

Functional Component功能组件

import React from 'react';
export const InputRender=(props)=>{
return(
        <input
        type="text"
        onChange={(e) => { props.updateName(e.target.value); }}
        value={props.name2} />
    )
}

Hope this helps!希望这可以帮助!

FYI, you can still make your changes work if you bind setState method to point to your class only, like仅供参考,如果您将setState方法绑定为仅指向您的 class ,您仍然可以使您的更改生效,例如

<InputRender name2={this.state.name2} setState={this.setState.bind(this)}/>

But I would not recommend this但我不推荐这个

You can wrap the setState in a function in parent component and then you can pass function as props to child component.您可以将 setState 包装在父组件的 function 中,然后您可以将 function 作为道具传递给子组件。 You can refer ReactJS call parent method可以参考ReactJS 调用父方法

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

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