我使用 Web 组件(特别是 polymer )已经有一段时间了,最近一直在尝试了解 React。我认为会有很多相似之处,尽管我没有在 React 中看到任何方法来根据其挂载的 DOM 节点的属性来影响组件的初始状态。
这可能吗,还是我错过了 React 的意图?能够以这种方式自定义组件似乎是使重用变得更容易的最明显的方法之一。
谢谢
最佳答案
React可以通过this.props
访问DOM Node的所有属性。
您可以设置 React 组件的状态,使其反射(reflect)初始属性的值,如下所示:
class MyComponent extends React.Component {
constructor(props) {
super(props);
// here you intialize the state of the component with the value of myAttribute
this.state = {myAttribute: props.myAttribute};
}
render() {
return (
<div>
The value of myAttribute is: {this.state.myAttribute}
</div>
);
}
}
现在,如果您更改 DOM 节点的属性并希望将此更改反射(reflect)在状态中,React 会为您提供一个名为 componentWillReceiveProps(nextProps)
的生命周期方法,您可以在其中更新状态像这样:
class MyComponent extends React.Component {
constructor(props) {
super(props);
// here you intialize the state of the component with the value of myAttribute
this.state = {myAttribute: props.myAttribute};
}
componentWillReceiveProps(nextProps) {
// here you update the state with the new value of myAttribute
this.setState({myAttribute: nextProps.myAttribute});
}
render() {
return (
<div>
The value of myAttribute is: {this.state.myAttribute}
</div>
);
}
}
您可以在此处找到带有示例的 JSFiddle http://jsfiddle.net/ko2jfqeL/
关于javascript - DOM 属性和 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37055120/