美文网首页
React学习--基础部分(一)

React学习--基础部分(一)

作者: innkk | 来源:发表于2018-04-03 08:56 被阅读0次

1.props

const element = <Welcome name="Sara" />

如果用户自定义了一个组件Welcome,可以传递他的jsx属性,我们把类似于name的属性叫做props.

2.state

不能直接修改state的值

同时更新几个值,state更新可能是异步的,一般这样写:

// Wrong
this.setState({
      counter: this.state.counter + this.props.increment,
        });
        
    // Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

3.自定义组件

通常自定义组件以大写开头.

如果一个组件被多次调用,可以将它抽象为一个函数,返回该组件

4.事件

阻止默认事件:e.preventDefault()

点击事件时需要bind

 If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
 if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.         

如果不习惯该用法,可以使用箭头函数

 <button onClick={(e) => this.handleClick(e)}>Click me
</button>

上面这种语法的问题是每次LoggingButton呈现时都会创建一个不同的回调。在大多数情况下,这是很好的。但是,如果将此回调传递给较低的组件,则这些组件可能会执行额外的重呈现。我们通常建议在构造函数中绑定或使用类字段语法,以避免这种性能问题。

点击事件传递参数

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

相关文章

网友评论

      本文标题:React学习--基础部分(一)

      本文链接:https://www.haomeiwen.com/subject/bqfqhftx.html