简体   繁体   中英

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 !

However I feel having 2 state elements isn't the right way to do this.

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.

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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