加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

【React】React.Component小结

发布时间:2020-12-15 05:12:20 所属栏目:百科 来源:网络整理
导读:React.Component 是一个抽象的Class,通常继承该类来构建自定义的Component。 Component可以将U分离成独立的碎片,有点类似于JavaScript的function,它接受一个任意的输入(props)并返回一个React element描述屏幕中的内容。 有两种方法构建Components 1 Ja

React.Component 是一个抽象的Class,通常继承该类来构建自定义的Component。 Component可以将U分离成独立的碎片,有点类似于JavaScript的function,它接受一个任意的输入(props)并返回一个React element描述屏幕中的内容。

有两种方法构建Components

1 JavaScript函数

function Welcome(props) {
  return <h1>Hello,{props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}
ReactDOM.render(
  <App />,document.getElementById('root')
);

注意: Component必须返回单个根元素,因而要用

将包住。

2 利用React.Component 创建

class Greeting extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       color: props.initialColor
    };

  }
  render() {
    return <h1>Hello,{this.props.name}</h1>;
  }
}

必须包含render()方法

Component 生命周期

1 Mounting (挂载)

  • constructor() // 构造函数
  • componentWillMount()
  • render()
  • componentDidMount()

2 Updating

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

3 Unmounting
-componentWillUnmount()

每个Component中有
setState()
通过this.setState({value: dddd}) 更新

Class Properties

-defaultProps

class CustomButton extends React.Component {
  // ...
}

CustomButton.defaultProps = {
  color: 'blue'
};

-displayName
string用来在调试中显示信息

-propTypes

class CustomButton extends React.Component {
  // ...
}

CustomButton.propTypes = {
  color: React.PropTypes.string
};

Instance Properties

props

<Greeting initialColor='blue' />

state 存储一些数据信息,如果不在render()中使用,则最好不要放在state中。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读