blog
blog copied to clipboard
react
JSX
- JSX代码外面括上小括号,防止分号自动插入
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
- 在编译之后呢,JSX 其实会被转化为普通的 JavaScript 对象。
- Babel 转译器会把 JSX 转换成一个名为
React.createElement()的方法调用。
// 注意: 以下示例是简化过的(不代表在 React 源码中是这样)
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world'
}
};
组件
- 警告:
组件名称必须以大写字母开头。
例如,<div /> 表示一个DOM标签,但 <Welcome /> 表示一个组件,并且在使用该组件时你必须定义或引入它。
- 警告:组件的返回值只能有一个根元素。这也是我们要用一个来包裹所有<Welcome />元素的原因。
function App() { return ( <div> <Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" /> </div> ); }- 所有的React组件必须像纯函数那样使用它们的props。
//纯函数,react要求使用纯函数,涉及到数据 function sum(a, b) { return a + b; }//会改变自身的输入值 function withdraw(account, amount) { account.total -= amount; }- 状态与属性十分相似,但是状态是私有的,完全受控于当前组件。
- 类组件应始终使用props调用基础构造函数。
生命周期
- 如果需要存储不用于视觉输出的东西,则可以手动向类中添加其他字段。
正确使用状态
不要直接更新状态 状态更新可能是异步的 状态更新合并
1. 因为 this.props 和 this.state 可能是异步更新的,你不应该依靠它们的值来计算下一个状态。
要修复它,请使用第二种形式的 setState() 来接受一个函数而不是一个对象。
this.setState( (prevState, props) => ({ counter: prevState.counter + props.increment }))-
数据自顶向下流动
-
你必须谨慎对待 JSX 回调函数中的 this,类的方法默认是不会绑定 this 的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined。 解决方法:
- 属性初始化器语法,你可以使用属性初始化器来正确的绑定回调函数:(这个语法在 Create React App 中默认开启。)
class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }- 如果你没有使用属性初始化器语法,你可以在回调函数中使用 箭头函数:
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> ); } }