简体   繁体   中英

react js getting data from a input field

I'm very new to reactjs and I've using AngularJS upto now. Currently i'm trying to learn reactjs.

I have a html code like this

 <div class="status_bar">

                <div>

                    <label class="status_head">Post as: John Smith</label>

                    <input class= 'post_data_input' placeholder="I'm seeking feedback for..."/>
                    .
                    <div class="status_down">

                        <button class="public_btn">Public</button>

                        <button class="post_btn">Post</button>
                        <img class='cam_btn'  src="img/cam.png" alt=""/>

                    </div>

                </div>

            </div>

I want to save whatever typed in the input field to an array and access that data from the array to show somewhere else. How can I do this in reactjs?

Thanks inadvance.

you can get it by two ways , either:

1- assign ref value myInput to input , and retrieve it by this.refs.myInput.value

2 - IF you are getting value on firing its own event , retrieve it by event.target.value


SAMPLE :

 class App extends React.Component { constructor() { super(...arguments); this.state= {}; } //Method-1 : this.refs.myInput.value onClick() { alert('You enter : '+this.refs.myInput.value); } // METHOD-2 : event.target.value onKeyUp(event) { const value = event.target.value; this.setState({inputSize: value.length || ''}) } render() { return (<div class="status_bar"> <div> <label class="status_head">Post as: John Smith </label> <input ref="myInput" className= 'post_data_input' placeholder="I'm seeking feedback for..." onKeyUp={this.onKeyUp.bind(this)} /> .<label>{this.state.inputSize}</label> <div className="status_down"> <button className="public_btn" onClick={this.onClick.bind(this)}>Public</button> <button className="post_btn" onClick={this.onClick.bind(this)}>Post</button> <img className='cam_btn' src="img/cam.png" alt=""/> </div> </div> </div>) } } // -- Mount component ReactDOM.render(<App />, document.querySelector('section')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <section></section> 

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