简体   繁体   中英

Interacting with React components from non-react world

We've an application that already uses KnockoutJS extensively. For Charting we are planning to use ReactJS. We could able to build simple charts with ReactJS easily. One of the question that puzzle my how can I interact with this React charts from a non-React world. Let me put an example. Let's say you've a bar chart React component and initially you want to render the chart with axes and so you do like below.

ReactDOM.render(<BarChart axes={true} data={data} {...lot of other props} />, mountNode);

Now let's assume you've a button that exists in a non-React world and on click of the button you want to hide the axes. How can I do that? Can I able to expose a public method in the BarChart component that can be invoked from outside?

For ex.,

const BarChart = React.createClass({

   ....

   showAxes(show) {
     //...
   }
});

var barChart = ReactDOM.render(<BarChart axes={true} data={data} {...lot of other props} />, mountNode);
barChart.showAxes(false);

But the axes is a prop not state and so even we expose a public method we cannot change the prop right? Any ideas how we can handle these things? How we can interact with React components from an non-react world?

You are right just expose the function and call the function from outside. You can store axes in state in the getinitialState

const BarChart = React.createClass({
   getInitialState(){
    return {
        axes: this.props.axes
     }
  }
   ....

   showAxes(show) {
     //...
     this.setState({
        axis: show
     })
   }
});

var barChart = ReactDOM.render(<BarChart axes={true} data={data} {...lot of other props} />, mountNode);
barChart.showAxes(false);

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