简体   繁体   English

这是“ React.js”方法吗?

[英]Is this the “React.js” way of doing this?

I'm starting with React and I tried to create a simple form that says Hello name ! 我从React开始,我试图创建一个简单的表单,上面写着Hello name

However I feel having 2 state elements isn't the right way to do this. 但是我觉得拥有2个状态元素不是执行此操作的正确方法。

Does anyone knows or believes there's a better way to do this? 有谁知道或认为有更好的方法可以做到这一点?

By the way, I know I can just bind the name state to the h2, but I want it to happen on click. 顺便说一句,我知道我可以将名称状态绑定到h2,但是我希望它在单击时发生。

    var Name = React.createClass({
                getInitialState:function(){
                    return {
                        inputname:'',
                        h2name:''
                    };
                },
                showName:function(event){
                    event.preventDefault();
                    this.setState({h2name:this.state.inputname}); 
                },
                updateName:function(event){
                    this.setState({inputname:event.target.value});
                }
                ,
                render:function(){
                    return (
                        <div>
                            <form onSubmit={this.showName}>
                                <input onChange={this.updateName} placeholder="Enter your name"></input>
                                <button type="submit">Show</button>
                            </form>
                            <h2>Hello {this.state.h2name}!</h2>
                        </div>
                    );
                }
            });
ReactDOM.render(<Name />,document.getElementById('mount-point'));

one state is enough. 一个状态就足够了。

var Name = React.createClass({
    getInitialState: function () {
        return {
            inputname: ''
        };
    },
    showName: function (event) {
        event.preventDefault();
        this.setState({ inputname: this.refs.inputname.value });
    },

    render: function () {
        return (
            <div>
                <input ref="inputname" placeholder="Enter your name"></input>
                <button onClick={this.showName}>Show</button>
                <h2>Hello {this.state.inputname}!</h2>
            </div>
        );
    }
});
ReactDOM.render(<Name />, document.getElementById('root'));

you can use refs to get the input value. 您可以使用引用来获取输入值。 I think you want this effect, here is the demo 我想你想要这种效果,这是演示

here is the document of refs more-about-refs 这是参考文献more-about-refs

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

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