简体   繁体   English

通过 react function 作为道具

[英]Passing react function as props

I've been looking around at other post but haven't found what is wrong with my code.我一直在查看其他帖子,但没有发现我的代码有什么问题。 It should pass a function down to the component as a prop, however I have dificulties accessing it as when I do I get the response that the it cannot read props of undefined.它应该将 function 作为道具传递给组件,但是当我收到它无法读取未定义道具的响应时,我很难访问它。 What am I doing wrong?我究竟做错了什么?

Props:道具:

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

Component:零件:

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 is undefined in your function. this在您的 function 中未定义。 Since undefined doesn't have any props, you can't access .props of it.由于undefined没有任何道具,因此您无法访问它的.props

You need to bind it to the component in your constructor, like so:您需要将其绑定到构造函数中的组件,如下所示:

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