LoginSignup
4
1

More than 5 years have passed since last update.

React Componentのkey

Last updated at Posted at 2017-03-29

下記Postコンポーネントからkey属性の値を読み取れない。key属性を設ける目的は、ただReactのVirtualDomを構築する時に役に立つだけです。

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);

Reactドキュメント

Lists and Keys

Full検証用ソースコード

class Post extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    // consoleログにundefinedが出力される
    console.log("component key:" + this.props.key);
    return (
      <div>
      <h3>{this.props.title}</h3>
      <p>{this.props.content}</p>
    </div>
    );
  }
}

function Blog(props) {
  const sidebar = (
    <ul>
      {props.posts.map((post) =>
        <li key={post.id}>
          {post.title}
        </li>
      )}
    </ul>
  );
  const content = props.posts.map((post) =>
    <Post key={post.id} title={post.title} content={post.content} />
  );
  return (
    <div>
      {sidebar}
      <hr />
      {content}
    </div>
  );
}

const posts = [
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
  <Blog posts={posts} />,
  document.getElementById('root')
);

参考記事

React.jsの地味だけど重要なkeyについて
ReactJS - Keys

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1