react 基础

一、render 函数 里面只能用一个标签

//正确
render () {
    return (<div>hello<div>)
}
//错误
render () {
    return (
        <div>hello<div>
        <div>world<div>
    )
}

二、state在组件在的定义、使用、以及改变

  • 定义
//在constructor函数中定义
constructor ( props ) {
    super(props);
    this.state = {
        inputValue:"",
        list:[]
    }
}
  • 使用
<input value = { this.state.inputValue} />
  • 改变
<input value = { this.state.inputValue} onChange = {this.changeInput.bind(this)} />
//方法一
changeInput(e){
    this.setState({
        inputValue:e.target.value
    })
}
//方法二
changeInput(e){
    const value = e.target.value;//须要保存变量,不能在下面直接用e.target.value,或者会报错
    this.setState(()=>({
        inputValue:value
    }))
}

三、注释写法

{/*注释*/}
//或者
{
//注释
}

四、css中的class与es6的class冲突,改用className来代替

五、laber标签和input作关联是所用的for 要用htmlFor来代替

六、父组件传值给子组件

//父组件经过属性的方式传给子组件
//父组件
<todoList content = {item} />
//子组件接受则用props
//子组件
<div>{this.props.content}</div>

七、子组件像父组件传参

//父组件经过属性传父组件的方法给子组件(注意:必须bind(this),不然子组件this指向有问题)
//父组件
<todoList delete = {this.delete.bind(this)} />
//子组件接受
delete(){
    this.props.delete();
}

八、PropTypes和defaultProps进行类型检查

查考文档 连接描述
//子组件
import PropTypes from 'prop-types';
class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  name: PropTypes.string
};

九、refs获取dom

参考文档 连接描述
相关文章
相关标签/搜索