javascript - DOM 属性和 React

标签 javascript reactjs polymer web-component

我使用 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/

相关文章:

javascript - 有没有办法删除 javascript 中表中与正则表达式匹配的所有行?

javascript - React 子组件不对状态变化使用react

dart - polymer 纸菜单无法在数据网格/表格上​​正确显示

关闭 shutter-reloaded.js 的 Javascript

javascript - 如何在 antd 中开始拖动 React DnD 表的特定行时显示工具提示?

java - 从客户端应用程序(React Js+Node Js)向 Java Web 服务发出请求

javascript - 在 Polymer 1.0 中使用选项卡切换 View

javascript - 向事件处理函数添加参数?

javascript - jquery 属性选择点击不起作用

javascript - 带有用于电子邮件的自定义 Sendgrid Controller 代码的 Strapi Beta