我试图弄清楚下面的代码如何在{ active, children, onClick }
方面起作用。在这里做什么花括号?我本来期望const Link = (props) =>
,使用props.active等在函数中访问值。这就是我在下面的CommentBox示例中所做的。
链接:
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>
)
}
FilterLink:
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'
const mapStateToProps = (state, ownProps) => {
return {
active: ownProps.filter === state.visibilityFilter
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
dispatch(setVisibilityFilter(ownProps.filter))
}
}
}
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
)(Link)
export default FilterLink
http://redux.js.org/docs/basics/ExampleTodoList.html
CommentBox:
const CommentBox = ( props ) =>
<div className="commentBox">
<h1>Comments</h1>
{ props.comments.valueSeq().map( (comment) =>
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
)}
<CommentForm />
</div>
function mapStateToProps(state) {
return {comments: state.get('comments')};
}
答案 0 :(得分:3)
const Link = ({ active, children, onClick }) => { ... });
这是做第一个论点的解构。假设您的第一个参数是一个至少具有active
,children
和onClick
属性的对象,它会直接将它们映射到同名变量。
您可以在行动here中看到它。
// ES6
function foo({bar, baz}, bam){
console.log(bar, baz)
}
// ES5
"use strict";
function foo(_ref, bam) {
var bar = _ref.bar;
var baz = _ref.baz;
console.log(bar, baz, bam);
}