我写了以下反应组件
class RegistrationActivity extends React.Component {
constructor(props) {
super(props);
this.state = {activity: this.props.activities[0]}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({activity: event.target.value}, () = {
this.props.handleChange(event.target.value)
})
}
render() {
return (
<div>
<div>Select Activity</div>
<div>
<select onchange={this.handleChange} value={this.state.activity}>
{
this.props.activities.map((activity, index) =>
<option>{activity}</option>
)
}
</select>
</div>
</div>
)
}
}
<RegistrationActivity handleChange={this.handleSelectionChange} activities=["foo", "bar", "baz"] />
我的目标如下
但是我收到了错误
SyntaxError: Inline Babel script: Unexpected token (45:59)
43 | }
44 | handleChange(event) {
> 45 | this.setState({activity: event.target.value}, () = {
| ^
46 | this.props.handleChange(event.target.value)
47 | })
48 | }
答案 0 :(得分:1)
错误是由于回调函数的ssyntax无效,您需要使用=>
而不是=
this.setState({activity: event.target.value}, () => { // => operator here
this.props.handleChange(event.target.value)
})
}
答案 1 :(得分:1)
handleChange(event) {
this.setState({activity: event.target.value}, () => {
this.props.handleChange(event.target.value)
})
}
您在功能中错过了=>
。
要从子组件调用父组件方法,则需要遵循以下结构。
class Parent extends React.Component {
triggerFoo() {
this.foo.toggle();
}
render() {
return (
<div>
<Foo ref={foo => this.foo = foo} />
<Button onClick={this.triggerFoo.bind(this)}/>
</div>
);
}
}
class Foo extends React.Component {
state = {foo: false}
toggle() {
this.setState({
foo: !this.state.foo
});
}
render() {
return (
<div>
Foo Triggered: {this.state.foo.toString()}
</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button onClick={this.props.onClick}>
Click This
</button>
);
};
}
ReactDOM.render(<Parent />, document.getElementById('root'));