react, Stateless Functions, ES6 花括号参数, Spread operator

下面是ES2015的语法。

Stateless Functions

例子一:

const FilterLink = (props) => {
	return (
		{props.children}
		
	)
}
Show all


例子二:

class FilterLink extends Component {
	render() {
		const props = this.props;
		return (
			{props.children}
		)
	}
}
Show all

这两个是一样的,因为react 提供许多state,比如说componentdidmount componentwillmount, 但是很多时候用不着,所以react 鼓励我们把这种简化的stateless function放在class里面用。所以第一个例子就是stateless function,简化了react的表达。

例子三:

const FilterLink = ({filter, children}) => {
	return (
		{children}
	)
}
Show all

这个跟例子一很类似,不同的是,例子一用一个props参数表示了父级传入的所有properties,而新的语法允许我们用{} object,这是因为这叫destruction,就是一一对应的props。比方说例子一里面有props.children, 在例子三就直接可以用children了,参照例子四。


Spread Operator

例子四:

const FilterLink = ({filter, children, className}) => {
	return (
		 {
			console.log("logging className!!! "+className+" This is destruction");
		}}>{children}
		
	)
}

Show all

结果在console里面会出现:logging className!!! heyhey This is destruction,

请再对比如下例子五:

const FilterLink = ({filter, children, ...something}) => {
	return (
		 {
			console.log("logging className!!! "+something.className+ "! " + something.test + "! " +"This is destruction");
			e.preventDefault();
		}}>{children}
		
	)
}
test="test">Show all

我们加了个新的property结果在console里面会出现:logging className !!!heyhey! test! This is destruction,


聪明的同学发现会结果是一样的。我把剩下的props都放进something里面了, 三个点叫 spread operation,用中文叫“xxx等”


 

你可能感兴趣的:(react, Stateless Functions, ES6 花括号参数, Spread operator)