简体   繁体   中英

How do I return values from a React component?

I made a slider component, using JQueryUI, which internally computes its current slider value. I am rendering it like this:

<Slider config={config} value={this.getValue} />

Inside the slider component I call this getValue() function and pass the current slider value:

this.props.value(this.state.sliderValue); 

In the jsx file where I rendered the component I can only retrieve the value of the slider inside the callback function getValue(). Is there any way I can directly get the value instead of inside the callback?

You can use a reference to the mounted component to get its state:

var Slider = React.createClass({
  getInitialState: function() {
    return {
      sliderValue: 5
    };
  },
  render: function() {
    return <div />;
  }
});

var mySlider = ReactDOM.render(<Slider />, document.body);
console.log(mySlider.state.sliderValue);

See more about using refs to components in the React docs .

not sure poking inside an Object is a wise idea. if the calling objects need to know of the inside of Slider than pushing the value up via a callback, and returning it down with a "value=" is the right thing to do. read about the difference of controlled vs uncontrolled objects in react: https://facebook.github.io/react/docs/forms.html

ps use value={this.getValue.bind(this)} that way getValue can save it to this so other methods can use it if needed

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