我试图理解为什么我们必须将对象null绑定到函数
add(text) {
this.setState(prevState=> ({
notes: [
...prevState.notes,
{
id: this.nextId(),
note: text
}
]
}))
}
render() {
return (
<div className="board">
{this.state.notes.map(this.eachNote)}
<button onClick={this.add.bind(null, "New Note")}
id="add">Add note</button>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我们为什么不能这样做this.add("New Note")?
我是新的反应,我想知道这是否是从输入表单获取值的正确方法(有点质量代码).从'react'导入React;
class Form extends React.Component {
constructor() {
super();
this.state = {
nameValue: '',
ageValue: ''
}
}
onChangeName(event) {
this.setState({
nameValue:event.target.value
});
}
onChangeAge(event) {
this.setState({
ageValue: event.target.value
});
}
showValue(){
alert('name '+ this.state.nameValue + ' age: ' + this.state.ageValue)
}
render() {
return (
<form>
<label>Name:
<input type="text" onChange={this.onChangeName.bind(this)}/>
</label>
<label>Age:
<input type="text" onChange={this.onChangeAge.bind(this)}/>
</label>
<input type="submit" value="Submit" onClick={this.showValue.bind(this)}/>
</form>
);
}
}
export default Form;
Run Code Online (Sandbox Code Playgroud)
我的意思是我听说它做出反应的方式是这样的,每个组件都应该有点独立,并且有自己的行为.顺便说一句代码的工作原理只是要求我从中获得项目的质量.或者我应该只是向按钮添加一个事件并使其他组件无状态,即2个输入字段
我正在做一个React Native项目。在一些教程中,我看到了绑定这样的方法:
constructor(props){
super(props);
this.my_function = this.my_function.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否可以使用构造函数访问函数,this.my_function然后为什么还要重新绑定呢?我有Java和Python的背景,也许这就是为什么我对这种类型的方法绑定感到困惑的原因。注意:我知道,如果我没有在React Native / React JS中绑定方法,那么我的方法将无法正常工作。我只想知道为什么我需要这种额外的绑定。