gpt4 book ai didi

javascript - 将 setState() 绑定(bind)到全局函数只会影响组件的一个实例

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:20 24 4
gpt4 key购买 nike

注意:我根据Nicholas Tower的回答修改后编辑了问题。

我有一个绑定(bind)到组件并更改其状态的全局函数。我想建立一个表单生成器系统。有一个名为 setLabel 的全局函数它绑定(bind)到名为 InputBox 的组件并改变它的状态。这个全局函数是通过另一个名为 ModalPanel 的组件触发的。它控制绑定(bind)组件的可编辑属性 InputBox .为了简化这个问题,我简化了函数和组件类。

这是全局函数:

function setLabel(postID, attributeName ){

var text = 'example';
if(text !== ''){

this.setState({ [attributeName] : text});

}
}

这是绑定(bind)到 setLabel 的组件功能。注意如何 setLabel函数从父级传递 InputBox子组件ModalPanel组件函数作为属性。

class InputBox extends Component{

constructor(props){
super(props);
this.state = {
placeholder : '',
maxlength: '',
type: '',
}

this.setLabel = setLabel.bind(this); // Binding this to the global function.
}

render(){

let elementId = "inputElement-" + this.props.idCounter;
let mainElement = <Form.Control
id = {elementId}
type = {this.state.type}
placeholder = {this.state.placeholder}
maxLength = {this.state.maxlength}
/>
return <Row>
<ModalPanel
handleHide = {this.props.handleHide}
handleShow = {this.props.handleShow}
setLabel = {this.setLabel}
/>
</Row>
}
}

最后,下面是 ModalPanel setLabel 所在的组件函数功能被触发。

function ModalPanel(props){

return(
......................
......................
......................
<Button variant="primary" onClick = {() => props.setLabel()}>Save changes</Button>
......................
......................
......................)
}

setLabel旨在设置 InputBox 状态的函数在 ModalPanel 中单击按钮时必须触发成分。问题是,有多个渲染 <InputBox />窗口上的组件,当我尝试使用此功能时,“状态更改”仅影响 <InputBox /> 的第一个实例成分。我想做的是,每个实例都应该有自己的内部状态和 setLabel()函数应该绑定(bind)到调用它的特定组件。因此,此函数可以设置不同组件实例的状态。我怎么能那样做?

添加:

请检查下面的链接以查看显示我的系统如何工作的 gif 图像。正如您所看到的,即使我选择了第三个输入框元素来编辑它的属性(在本例中,设置它的占位符文本),第一个元素也会发生变化。

Go to gif

最佳答案

在开头添加一个this.,如:

this.setLabel = setLabel.bind(this); 

现在您要在 InputBox 的实例上设置一个属性。稍后在组件中引用它时,请确保使用 this.setLabel 引用它。

关于javascript - 将 setState() 绑定(bind)到全局函数只会影响组件的一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56971611/

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