如何通过Key in React查找元素?

时间:2016-10-13 12:26:41

标签: reactjs

<ul>
    <li key='search1'>1234</li>
    <li key='search2'>5678</li>
    <li key='search3'>9</li>
</ul>

如何按键查找元素并更改元素值,如addClass / innerHtml?

注意:在Plain React中 - 没有Flux或Jsx。

2 个答案:

答案 0 :(得分:3)

在React中删除了对key的访问权限。

  

props key和ref已经保留了属性名称。
  ...
  您无法再从Component实例本身访问this.props.ref和this.props.key。   https://facebook.github.io/react/blog/2014/10/16/react-v0.12-rc1.html#breaking-change-key-and-ref-removed-from-this.props

您可以简单地使用其他名称(例如&#39; reactKey&#39;)并通过道具访问它。这是一个演示:http://codepen.io/PiotrBerebecki/pen/PGaxdx

class App extends React.Component {
  render() {
    return (
      <div>
        <Child key="testKey1" keyProp="testKey1"/>
        <Child key="testKey2" keyProp="testKey2"/>
        <Child key="testKey3" keyProp="testKey3"/>
        <Child key="testKey4" keyProp="testKey4"/>
      </div>
    );
  }
}

class Child extends React.Component {
  render() {
    console.log(this.props);  // only 'keyProp' is available

    let getClassName = () => {
      switch (this.props.keyProp) {
        case 'testKey1': 
          return 'red';
        case 'testKey2': 
          return 'green';
        case 'testKey3': 
          return 'blue';
        default: 
          return 'black';
       }
    };

    return (
      <div className={getClassName()}>
        Some Text
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

答案 1 :(得分:1)

如果要访问React元素的DOM节点,请使用ref属性。
但是,在大多数情况下,您无需使用参考即可实现所需的功能,因此请确保您没有滥用此功能。

以下是来自React文档的一些信息:Refs and the DOM - React

引用和DOM

  

引用提供了一种方法,可以访问在render方法中创建的DOM节点或React元素。

何时使用参考

  

裁判有一些很好的用例:

     
      
  • 管理焦点,文本选择或媒体播放。
  •   
  • 触发命令性动画。
  •   
  • 与第三方DOM库集成。
  •   
     

避免将refs用于可以声明式完成的任何事情。

创建参考

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

访问参考

const node = this.myRef.current;