React Js之组件(Component)与state

  React Js组件:

    组件(Component)是为了更好的维护我们的应用,可以在不影响其他的组件的情况下更新或者更改组件。

    state:是标记数据的来源,我们使state比较简单和单一,如果我们有是个相应的state,我们应该进行相应的封装,我们应该创建一个容器组件来保存所有的值。

    如下面代码:

  import React from 'react'
  class App extends React.Component{

  //有状态的值
  constructor(){
  super();

  this.state = {
  data:[
  {"id":"1","name":"rtony","age":"20"},
  {"id":"2","name":"xuanyi","age":"20"},
  {"id":"3","name":"tony","age":"20"},
  {"id":"4","name":"jimeth","age":"20"},
  ]
  }
  }

  render(){
  return (
  <div>
  <Header />
  <Content/>
  <table>
  <tbody>
  {/****注意这里是使用key={i}在map方法中,这将有助于之更新必要的元素,而不是在发生变化时重新绘制整个列表,对于大量动态创建的元素来说,这是一个巨大的性能提升****/}
  {this.state.data.map((person,i) => <TableRow key={i} data={person} />)}
  </tbody>
  </table>
  </div>
  );
  }
  }
class Header extends React.Component{
render(){
return(
<div>
<h1>header</h1>
</div>
);
}
}

class Content extends React.Component{
render(){
return (
<div>
<h2>Content</h2>
<p>this is a content!</p>
</div>
);
}
}

class TableRow extends React.Component{
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td>{this.props.data.name}</td>
<td>{this.props.data.age}</td>
</tr>
);
}
}
export default App;
上面的例子中,有三个组件,这三个组件将app的界面分为了三个部分,一个是App主组件,还有其余的子组件header和content,这使界面更容易维护和更新,加入我们需要修改header或者content的内容,只需要改相应的组件就可以了。
原文地址:https://www.cnblogs.com/tonylovett/p/7614727.html