繁体   English   中英

通过 react function 作为道具

[英]Passing react function as props

我一直在查看其他帖子,但没有发现我的代码有什么问题。 它应该将 function 作为道具传递给组件,但是当我收到它无法读取未定义道具的响应时,我很难访问它。 我究竟做错了什么?

道具:

<SettingsSection    forceUpdateHandler = {this.props.forceUpdateHandler}
                                        languages = {this.props.languages}
                                        setLanguage = {this.props.setLanguage}
                                        getLanguage = {this.props.getLanguage}
                                        getParameters = {this.props.getParameters}/>

零件:

class SettingsSection extends Component{

    constructor(props){
        super(props)
        this.state = {
            value: "java"
        }
    }

    // Send change in component upwards.
    handleChange(event) {
        this.props.setLanguage(event.target.value);
    }

    // Render component.
    render() {
        return (
            <div>
                {/*settings section will be changed later*/}
                <h5 style={{paddingTop:"20px"}}>Settings</h5>

                {/* Language drop down menu */}
                <h6 style={{paddingTop:"15px"}}>Export Language</h6>
                <select style={{paddingTop:"5px"}} onChange={this.handleChange} value={this.state.value}>
                    {this.props.languages.map(language => { return ( <option value={language}> {language} </option>)})}
                </select>
            </div>
        );
    }
}

this在您的 function 中未定义。 由于undefined没有任何道具,因此您无法访问它的.props

您需要将其绑定到构造函数中的组件,如下所示:

constructor(props){
        super(props)
        this.state = {
            value: "java"
        }
        this.handleChange = this.handleChange.bind(this);
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM