以 ReactJS 形式传递事件

Passing Events in ReactJS Form

我正在尝试使用 React 创建一个组件,我有 2 个 classes(具有状态的 App class 和具有下拉菜单的 ImageType class select 和选项)。 当我在 ImageType class 中创建 selection 时,我想更改 App 中的状态,但出现错误(out.js:6 Uncaught TypeError: Cannot read 属性 'value' 个未定义)。 我知道我做错了什么,但我不知道是什么。 我希望选项标签的 "value" 成为 this.state.field 的新值 谢谢

class ImageType extends React.Component{

    onDone=()=>{
        if(typeof this.props.done === "function"){
            this.props.done(this.props.imageType)
        }
    }

    render(){
        return(
            <div>
                <select value={this.props.imageType} onChange={this.onDone}>
                    <option value="illustration">Illustration</option>
                    <option value="vector">Vector</option>
                </select>
            </div>
        )
    }

}

class App extends React.Component{

    state={
        field:""
    }

    done = (event) =>{
        this.setState({
            field: event.target.value
        })
    }

    render(){
        return(
            <div>
                <ImageType imageType={this.state.field} done={this.done}/>
            </div>
        )
    }
}

ImageComponent中你必须在onDone函数中传递事件

// replaced brackets with event
onDone = event => {
  if(typeof this.props.done === "function"){
    this.props.done(event)
  }
}

@Spartacus 是对的,因为 this.props.done 函数接受一个 event 参数,你不应该传递一个 this.props.imageType 不是 event 类型。

或者您可以将选择的图像类型传递给 App 组件中的回调。

ImageType 组件

onDone = event => {
  if (typeof this.props.done === "function") {
    this.props.done(event.target.value);
}};

将选择的值传递给App组件中的回调函数,

应用组件

done = imageType => {
  this.setState({
    field: imageType
});};

check the demo here