简体   繁体   中英

React.js How to find ref element in inner component

I want to share data with < Filtering /> component from onChange event to parent component < ViewTwoComponent /> I don't know how to do it

Do you know maybe how to share data between component and his parent

ViewTwoComponent they don't see ref value and i don't know why?

On console is error: Uncaught TypeError: Cannot read property 'getDOMNode' of undefined

var ViewTwoComponent = React.createClass({
    "getInitialState": function() {
        return {
            "userTextValue": "hello11111111111111",
            "userTextRef": "userTextRef"
        }
    },
    "updateState": function(value) {
        this.setState({userTextValue: value })
    },
    "handleChange": function() {
        this.updateState(this.refs.userTextRef.getDOMNode().value)
    },
    "render": function() {
        return <div>
            <Inner />
            <Filtering refName={this.state.userTextRef} handleChange={this.handleChange} userTextValue={this.state.userTextValue} />
        </div>;
    }
})

var Inner = React.createClass({
    "render": function() {
        return <span>INNER</span>;
    }
});

var Filtering = React.createClass({
    "render": function() {
        return <span>
            <input type="text" ref={this.props.refName} onChange={this.props.handleChange} value={this.props.userTextValue} />
        </span>;
    }
});

React.render(< ViewTwoComponent />, document.getElementById("inner"))

It's a bit confusing what you mean when you try to reference this.refs.userTextRef but I'm assuming you want the value that's in your state. I'm also going to assume that the value of the key userTextRef is not actually userTextRef . You could try accessing the value by using square brackets.

  "handleChange": function() {
    this.updateState(this.refs[userTextRef]getDOMNode().value)
  }

I am new to React, but from what I remember of the tutorials, you should be passing a function of the Filtering component to the ViewTwoComponent .

var Filtering = React.createClass({
        "childChanged" : function(child, value) {
           console.log("child: " + child + "change value to: " value);
        },
        "render": function() {
            return <span>
                <input type="text" ref={this.props.refName} onChange={this.props.handleChange} value={this.props.userTextValue} notifyParent={this.childChanged} />
            </span>;
        }
    });

And then, in the handleChange method of the ViewTwoComponent class, you call this.props.notifyParent(this, this.state.userTextValue);

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