我有以下内容:
import React from 'react';
import {render} from 'react-dom';
class TShirt extends React.Component {
render () {
return <div className="tshirt">{this.props.name}</div>;
}
}
class FirstName extends React.Component {
constructor(props) {
super(props);
this.state = {
submitted: false
};
}
getName () {
var name = this.refs.firstName.value;
this.setState({ submitted: true }, function() {
this.props.action(name);
});
}
render () {
return (
<div>
<h2>tell us your first name</h2>
<form>
<input
type="text"
ref="firstName"
onChange={this.getName.bind(this)}
/>
<div className="buttons-wrapper">
<a href="#">back</a>
<button>continue</button>
</div>
</form>
</div>
);
}
}
class Nav extends React.Component {
render () {
return <p>navigation</p>;
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ''
};
}
getName (tshirt) {
this.setState({ name:tshirt })
}
render () {
return (
<section>
<Nav />
<TShirt name={this.state.name} />
<FirstName action={this.getName} />
</section>
);
}
}
render(<App/>, document.getElementById('app'));
我尝试使用来自“FirstName”组件的 onChange 方法(使用 props)的值来更新“TShirt”组件。
我在包装器内有一个整体状态来控制一切,但是当我开始在输入中键入名称时,我收到此错误:
未捕获类型错误:this.setState 不是函数
引用:
getName (tshirt) {
this.setState({ name:tshirt })
}
最佳答案
您必须将 getName
函数绑定(bind)到 this
。
在你的构造函数中放入
this.getName = this.getName.bind(this);
你的构造函数应该看起来像
constructor(props) {
super(props);
this.state = {
name: ''
};
this.getName = this.getName.bind(this);
}
关于javascript - 在更改方法上使用输入子项来 react 控件父级状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554855/