react(一)

react中使用JSX的原因:

在javascript代码中将JSX和UI放在一起时,会在视觉上有辅助作用,它还可以使React现实更多有用的错误和警告消息

react在渲染所有输入内容之前,默认转义的作用:

可以有效防止XSS(跨站脚本攻击)。

Babel会把JSX转译为一个名为React.createElement()函数调用

如何把React集成进一个已有应用:

可以在应用包含任意多的独立根节点。想要将一个React元素渲染到根DOM节点中,只需把它们一起传入ReactDom.render()

ReactDOM.render(element, document.getElementById('root'));```

##渲染组件
```function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

组合组件

组件在其输出中引用其他组件,就可以让我们用同一组件来抽象出任意层次的细节。

提取组件

将组件拆分为更小的组件

props是只读的:

组件无论使用函数声明还是通过class声明,都绝不能修改自身的props

this.handClick = this.handleClick.bind(this);

为了在回调中使用this,这里的绑定必不可少,未绑时this为undefined
原因:与js函数工作原理有关,如果没有在方法后面添加(),onClick={this.handleClick},你应该为这个方法绑定this

  constructor (props) {
    super (props);
    this.state = {isToggleOn: true};
    this.handleClick = this.handleClick.bind (this);
  }
  handleClick () {
    this.setState (state => ({
      isToggleOn: !state.isToggleOn,
    }));
  }
  render () {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}```

```class ActionLink extends React.Component {
  constructor (props) {
    super (props);
    this.state = {isToggleOn: true};
    this.handleClick = this.handleClick.bind (this);
  }
  handleClick = () => {
    console.log ('this is:', this);
  };
  render () {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}```

```class ActionLink extends React.Component {
  constructor (props) {
    super (props);
    this.state = {isToggleOn: true};
    // this.handleClick = this.handleClick.bind (this);
  }
  handleClick = () => {
    console.log ('this is:', this);
  };
  render () {
    return (
      <button onClick={() => this.handleClick ()}>
        Click me
      </button>
    );
  }
}```

```<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
上面两种方式等价

条件渲染

表单

受控组件:输入的值由React的state驱动。
input/textarea/select之类的标签都接受一个value属性,可以使用它来实现受控组件。

状态提升

多个组件需要反映相同的变化数据,可以将共享状态提升到最近的共同组件中去。

组件间的包含关系

某些组件无法提前知晓它们子组件的具体内容,在Sidebar和Dialog等共同容器中常用。对于这些组件可以用children prop来将子组件传递到渲染结果中。
少数情况下,可能需要在一个组件中预留出几个“洞”,将所需内容传入props,可以不使用children,并使用响应的prop,类似于插槽。

组件的特例关系

一些组件是其他组件的特殊实例。如RightSideBar 是SideBar的特殊实例,特殊组件可以通过props定制并渲染一般组件。

继承

组件可以直接引入 import 而无需 extend 继承

一个组件原则上只负责一个功能,如果需要负责更多功能,就应该考虑拆分成更小的组件。

React单向数据流

用React创建一个静态版本(需要创建一些会重用其他组件的组件,然后通过props传入所需的数据) -》通过props接受数据模型,如果数据模型发生变化,再次调用ReactDOM.render,UI就会相应更新。

检查相应数据是state需要满足下面条件:

1.非父组件通过props传递来的 2.随时间推移发生变化 3.非通过其他state或props计算出来

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。