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

Ant*_*der 19 reactjs

<ul>
    <li key='search1'>1234</li>
    <li key='search2'>5678</li>
    <li key='search3'>9</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

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

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

Pio*_*cki 6

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

props 键和 ref 已经是保留的属性名称。
...
您不能再从 Component 实例本身内部访问 this.props.ref 和 this.props.key 。 https://facebook.github.io/react/blog/2014/10/16/react-v0.12-rc1.html#break-change-key-and-ref-removed-from-this.props

您可以简单地使用不同的名称(例如'reactKey')并通过道具访问它。这是一个演示: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')
);
Run Code Online (Sandbox Code Playgroud)

  • 我想要做的是找到一个列表元素并添加一个类 (4认同)