React.js程序员

react 官方文档学习笔记

2017-07-04  本文已影响0人  Bruce陈

本文是我在重新学习react文档时针对自己之前忽视或易被忽视细节的整理,对应的React版本v15.6.1。原文react官方文档
这篇文章初衷是帮助自己加深记忆和理解,如有我理解不对的地方,还请大家指正。

Hello World

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

JSX

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

渲染Element

组件和属性(props)

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

基于class会有额外的特性,后续展开

State和生命周期

constructor(props) {
    super(props);
    this.state = {date: new Date()};
}

注意由于继承时子类没有自己的this,一定要调用super(props)

this.setState({
    date: new Date()
});

从而来修改state

this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));
<FormattedDate date={this.state.date} />

事件绑定

<button onClick={activateLasers}>
  Activate Lasers
</button>

但是不能通过return false;来阻止默认行为发生,一定要调用e.preventDefault();实现

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

原因在于我们是通过onClick={this.handleClick}读取的函数方法,而不是this.handleClick()
方法二是借助property initializer syntax,如下(create-react-app中可用)

// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
handleClick = () => {
  console.log('this is:', this);
}

方法三基于箭头函数,因为箭头函数的作用域在定义时被决定

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

方法三中每次渲染时会绑定不同的函数,因而可能触发组件的再次渲染,因而推荐方法一、二

条件渲染

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

Lists and Keys

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
);

Forms

Controlled Components

<input type="text" value={this.state.value} onChange={this.handleChange} />

那么它所显示的值就是this.state.value,通过onChange中绑定的函数修改this.state.value,从而控制这个表单元素输入的值,让其随用户输入而更新

Lifting State Up

对于一个在多个组件间需要同步的数据,可以将其提升到最近的共同祖先组件的stete上,之后通过props传递给各个子组件,使各个子组件中取到同一个值。也是是自顶向下数据流思想的一种体现

Composition vs Inheritance(组成与继承)

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}
function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

Thinking in React

上一篇 下一篇

猜你喜欢

热点阅读