最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react js , get siblings or parent value - Stack Overflow

programmeradmin0浏览0评论

I'm new to react, I'm curious how to do this properly. suppose I have this form, by clicking button, I want to get textbox value,

var form = React.createClass({
   submit : function(e){
      //how to get textbox value?
   },
   render : function(){
   return (
      <form>
         <input type="text" id="textbox" value="hey, get me"/>
         <button onClick={this.submit}>Get it</button>
      </form>
      );
   }
});

Any answer will be appreciated! thank you!

I'm new to react, I'm curious how to do this properly. suppose I have this form, by clicking button, I want to get textbox value,

var form = React.createClass({
   submit : function(e){
      //how to get textbox value?
   },
   render : function(){
   return (
      <form>
         <input type="text" id="textbox" value="hey, get me"/>
         <button onClick={this.submit}>Get it</button>
      </form>
      );
   }
});

Any answer will be appreciated! thank you!

Share Improve this question asked Sep 26, 2016 at 1:19 AnggerAngger 8056 gold badges15 silver badges32 bronze badges 3
  • 1 You don't want to interact with the DOM like this with React – Mark C. Commented Sep 26, 2016 at 1:25
  • how it should be? @MarkC. – Angger Commented Sep 26, 2016 at 1:27
  • 1 you should use managed components in component state - read the react docs – erik-sn Commented Sep 26, 2016 at 1:29
Add a comment  | 

3 Answers 3

Reset to default 8

React enforces parent-to-child unidirectional data flow. So, there's no simple way to access data from siblings.

But, if a child changes the state across the component, you probably want a state for keeping a track of that.

Sample code:

var FormBox = React.createClass({
  getInitialState: function () {
    return {
      textBox: 'hey, get me!'
    }
  },
  pressButton: function () {
    alert(this.state.textBox)
  },
  textChange: function (e) {
    this.setState({
      textBox: e.target.value
    })
  },
  render: function () {
    return (
      <form action='.'>
        <input type='text' placeholder={this.state.textBox} onChange={this.textChange}/>
        <button onClick={this.pressButton}> Get it </button>
      </form>
    )
  }
})

ReactDOM.render(<FormBox />, document.getElementById('root'))

JSBin demo: https://jsbin.com/koxujuwope/edit?js,output

Also, just a suggestion... You should move to ES2015

One way to accomplish this is using refs.

After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from render(). link to refs docs

Refs are basically the html elements / react instances you want to access. In this case, we want to get Input html element. We get input element by this.inputValue. Then read its value by usual js rule.

 var form = React.createClass({
       submit : function(e){
          e.preventDefault();
          console.log(this.inputValue.value);
       },
       render : function(){
       return (
          <form onSubmit={this.submit}>
             <input type="text" id="textbox" defaultValue="hey, get me"
               ref={ function(node){ this.inputValue = node }.bind(this) }
             />
             <button onClick={this.submit}>Get it</button>
          </form>
          );
       }
    });

here is a jsfiddle for your example, you can check the console for the input value.

Another way to accomplish the same thing is to make your input a controlled element. That means you assign input's value attribute to this.state.inputValue and you pass a onChange event handler as onChange={yourInputHandlerFunction}.

See the answer which explains this way of accomplishing the same thing.

The following code helps me to setup communication between two siblings. The setup is done in their parent during render() and componentDidMount() calls. It is based on https://reactjs.org/docs/refs-and-the-dom.html

class App extends React.Component<IAppProps, IAppState> {
    private _navigationPanel: NavigationPanel;
    private _mapPanel: MapPanel;

    constructor() {
        super();
        this.state = {};
    }

    // `componentDidMount()` is called by ReactJS after `render()`
    componentDidMount() {
        // Pass _mapPanel to _navigationPanel
        // It will allow _navigationPanel to call _mapPanel directly
        this._navigationPanel.setMapPanel(this._mapPanel);
    }

    render() {
        return (
            <div id="appDiv" style={divStyle}>
                // `ref=` helps to get reference to a child during rendering
                <NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
                <MapPanel ref={(child) => { this._mapPanel = child; }} />
            </div>
        );
    }
}
发布评论

评论列表(0)

  1. 暂无评论