我正在阅读官方的redux教程。
http://redux.js.org/docs/basics/UsageWithReact.html
在文件
中 components/Link.js
具有以下代码
import React, { PropTypes } from 'react'
const Link = ({ active, children, onClick }) => {
if (active) {
return <span>{children}</span>
}
return (
<a href="#"
onClick={e => {
e.preventDefault()
onClick()
}}
>
{children}
</a>
)
}
Link.propTypes = {
active: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func.isRequired
}
export default Link
我想知道为什么函数链接接受由花括号包围的变量。其次,if块中的return语句具有span
jsx标记而没有大括号,但其次,if <a>
标记的if块之外的return语句具有大括号。谁能解释为什么?
编辑:在从答案中找到关于解构分配后,我阅读了以下关于如何在函数中使用它的文章,这对我来说非常清楚。 https://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/
答案 0 :(得分:1)
function参数使用destructuring assignment从对象中提取值。
JSX周围的大括号是为了保持缩进清洁。
你可以这样做:
return <div>
lol
</div>
但你不能这样做:
return
<div>
lol
</div>
因此,为了保持JSX的缩进清晰,你必须用大括号包装标记。
答案 1 :(得分:1)
那是stateless function,当他们没有状态和生命周期方法时,你可以将反应类定义为普通的JS函数
花括号放在那里使用一个名为Destructuring的惊人es6功能。
基本上使用与执行相同的es6:
const Link = (props) => {
const { active, children, onClick } = props;
...
如果不使用ES6,它将与执行相同:
const Link = (props) => {
const active = props.active;
const children = props.children;
const onClick = props.onClick;
....
关于返回,当jsx元素超过1行时,使用括号。