下面是ES2015的语法。
Stateless Functions
例子一:
const FilterLink = (props) => {
return (
<a href='#'>{props.children}
</a>
)
}
<FilterLink >Show all</FilterLink>
例子二:
class FilterLink extends Component {
render() {
const props = this.props;
return (
<a href='#'>{props.children}</a>
)
}
}
<FilterLink >Show all</FilterLink>
这两个是一样的,因为react 提供许多state,比如说componentdidmount componentwillmount, 但是很多时候用不着,所以react 鼓励我们把这种简化的stateless function放在class里面用。所以第一个例子就是stateless function,简化了react的表达。
例子三:
const FilterLink = ({filter, children}) => {
return (
<a href='#'>{children}</a>
)
}
<FilterLink filter='SHOW_ALL' >Show all</FilterLink>
这个跟例子一很类似,不同的是,例子一用一个props参数表示了父级传入的所有properties,而新的语法允许我们用{} object,这是因为这叫destruction,就是一一对应的props。比方说例子一里面有props.children, 在例子三就直接可以用children了,参照例子四。
Spread Operator
例子四:
const FilterLink = ({filter, children, className}) => {
return (
<a href='#'
onClick={e => {
console.log("logging className!!! "+className+" This is destruction");
}}>{children}
</a>
)
}
<FilterLink filter='SHOW_ALL' className="heyhey">Show all</FilterLink>
结果在console里面会出现:logging className!!! heyhey This is destruction,
请再对比如下例子五:
<span style="font-size:14px;">const FilterLink = ({filter, children, ...something}) => {
return (
<a href='#'
onClick={e => {
console.log("logging className!!! "+something.className+ "! " + something.test + "! " +"This is destruction");
e.preventDefault();
}}>{children}
</a>
)
}
<FilterLink filter='SHOW_ALL' className="heyhey" <strong style="background-color: rgb(255, 0, 0);">test="test"</strong>>Show all</FilterLink></span>
我们加了个新的property结果在console里面会出现:logging className !!!heyhey! test! This is destruction,
聪明的同学发现会结果是一样的。我把剩下的props都放进something里面了, 三个点叫 spread operation,用中文叫“xxx等”