如何将Props传递给reactjs处理程序?

时间:2018-05-29 05:54:54

标签: reactjs

如何将Props传递给reactjs处理程序? 这是我的代码

var CommentForm = React.createClass({ 
     handleAuthorChange: function (e) {
            this.setState({ author: e.target.value });
        },
        handleTextChange: function (e) {
            this.setState({ text: e.target.value });
        },
    });

2 个答案:

答案 0 :(得分:1)

render()方法

<MyComponent onChnageChange=this.handleAuthorChange.bind(this,this.prop.myProp) />

并将此道具传递给您的处理程序

handleAuthorChange: function (e,props) {
            this.setState({ author: e.target.value });
            const myProp=props;
        }

答案 1 :(得分:0)

尝试这样的事情

var CommentForm = React.createClass({
    getInitialState: function () {
        return { author: '', text: '' };
    },
    handleAuthorChange: function (e) {
        this.setState({ author: e.target.value });
    },
    handleTextChange: function (e) {
        this.setState({ text: e.target.value });
    },
    handleSubmit: function (e) {
        e.preventDefault();
        var author = this.state.author.trim();
        var text = this.state.text.trim();
        if (!text || !author) {
            return;
        }
        this.props.onCommentSubmit({ author: author, text: text });
        this.setState({ author: '', text: '' });
    },
        render: function () {
            return (
                <form className="commentForm" onSubmit={this.handleSubmit}>
                    <input
                        type="text"
                        placeholder="Your name"
                        value={this.state.author}
                        onChange={this.handleAuthorChange}
                    />
                    <input
                        type="text"
                        placeholder="Say something..."
                        value={this.state.text}
                        onChange={this.handleTextChange}
                    />
                    <input type="submit" value="Post" />
                </form>
            );
        }
});