用了大约两天时间,第三次阅读了 React 的 Docs,整理出一些之前没有注意到的 React 的语法与使用原则。随后会附上 Sample Code & Translation.
this.props.childrenreturns nested elements inthiselement.
this.props.children返回this中的嵌套标签。md.render(this.props.children.toString())converts markdown to HTML Elements. (Plugin: Remarkable)
md.render(this.props.children.toString())可以将 Markdown 转换成 HTML 标签。JSX prevents injection attacks. It's safe to embed user input in JSX.
JSX 具备注入保护功能。在 JSX 中嵌入用户输入是安全的。All React Components must act like pure functions with respect to their props.
所有的 React 组件 必须表现的像纯函数,并与其属性( props )关联。-
Class components should always call the base
constructorwithprops.
类组件必须调用基本构造函数constructor并传入props参数。class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( <div> <h1>Hello World!</h1> <h2>It's {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } -
Lifecycle Hooks(生命周期钩子):
- Pay attention to
componentWillUnmount.
注意合理使用componentWillUnmount函数。(比如解除计时器任务)
- Pay attention to
If something is not used in
render(), it SHOULD NOT be instate.
在render()函数中用不到的东西,不应该出现在state里。-
this.propsorthis.statemay be updated asynchronously, DO NOT rely on their values for calculating the next state.
this.props或者this.state可能会被异步更新,所以不要通过他们的值来计算下一个状态的值。-
One way to meet this need: Use a second form of
setState()that accepts a function rather than an object.
一种符合需求的方法:使用setState()的第二种形式,它接收一个函数参数而不是一个对象。this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
-
-
React's Data Flow( React 的数据流):
- "Top-Down" or "Unidirectional"
自顶向下 / 单向数据流 - Children don't know where data come from.
子元素并不知道数据的来源。
- "Top-Down" or "Unidirectional"
-
You CANNNOT return
falseto prevent default behavior in React. You MUST callpreventDefault()explicitly.
在 React 中,不能通过返回false来阻止默认行为。必须显式地调用preventDefault()函数。// Wrong <a href="#" onclick="console.log('The link was clicked.'); return false"> Click me </a> // Right function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( <a href="#" onClick={handleClick}> Click me </a> ); } -
"
thisBinding" is necessary to makethiswork in the callback.
“this绑定”的目的是使this在回调函数中能正常工作。this.handleClick = this.handleClick.bind(this)In JavaScript, class methods are not bound by default.
在 JavaScript 中,类方法默认不会绑定。-
Fix 1: Property Initializer 属性初始化
handleClick = () => { console.log('this is:', this); } -
Fix 2 (Not Recommend): Arrow Function 箭头函数
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> ); } }- The problem with this syntax is that a different callback is created each time the
LoggingButtonrender. If this callback is passed as a prop to lower components, those components might do an extra re-rendering.
- The problem with this syntax is that a different callback is created each time the
-
use
ifconditions to render part of the component.
使用if条件语句控制组件渲染。// One Special Format: if statement in JSX render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> {isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> )} </div> ); } return
nullto hide a component. (Combined withstate)
通过返回null隐藏一个组件。-
A
keyshould be provided for list items.
列举元素时,应当为每一个元素提供一个key。-
keys help React identify which items have changed, are added, or are removed.keys should be given to the elements inside the array to give the elements a stable identity.
key可以帮助 React 识别哪一个元素被改动、被添加或者被删除了。key应该被置于数组内的标签中,以此提供一个稳定的标识。
const content = props.posts.map((post) => <div key={post.id}> <h3>{post.title}</h3> <p>{post.content}</p> </div> ); -
keys MUST ONLY be unique among siblings.
key在兄弟标签之间必须是唯一的。-
keys don't get passed to your components.
key属性不会传递给组件。- To pass them, you need to create a new
propwith another name.
新建一个其它名字的属性保存key的值以传递它。
- To pass them, you need to create a new
In React, a
<textarea>uses avalueattribute to get the content instead of HTML'schildren.
在 React 中,<textarea>使用value属性而不是 HTML 提供的children属性获取内容。-
Instead of use
selectedattribute on<option>, React usevalueon<select>to initial selected item.
React 通过初始化<select>的value属性来指定初始的选中元素,而不是使用<option>的selected属性。render() { return ( <form onSubmit={this.handleSubmit}> <label> Pick your favorite La Croix flavor: <select value={this.state.value} onChange={this.handleChange}> <option value="grapefruit">Grapefruit</option> <option value="lime">Lime</option> <option value="coconut">Coconut</option> <option value="mango">Mango</option> </select> </label> <input type="submit" value="Submit" /> </form> ); } When you need to handle multiple controlled
inputelements, you can add anameattribute to each element and let the handler function choose what to do based on the value ofevent.target.name.setState()will automatically merges a partial state into the current state.
setState()函数会自动将部分状态与当前状态合并。If something can be derived from either
propsorstate, it probably shouldn't be in thestate.
如果某些元素既可以放在props里又可以放在state里,那么它不应当被放在state里。DONOT use
stateat all to build static version of your app for it's reserved only for interactivity.
构建应用的静态版本时不应当使用state,因为state是用来实现交互的。Figure out the absolute minimal representation of the state your app needs and compute everything else you need on-demand.
找出应用的最小状态代表,并计算一切其它需要的值。