[英]React.js & […] (spread) syntax
基於頁面中的示例: https : //redux.js.org/basics/usage-with-react
我們有以下項目:
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
)
Todo.propTypes = {
onClick: PropTypes.func.isRequired,
completed: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}
此外,我們還有:
const TodoList = ({ todos, onTodoClick }) => (
<ul>
{todos.map((todo, index) => (
<Todo key={index} {...todo} onClick={() => onTodoClick(index)} />
))}
</ul>
)
有人可以告訴我上面代碼中的{... todo}是什么嗎?
我知道...運算符是一種擴展語法,可以說[... todos,newTodoItem](將新的待辦事項與舊的待辦事項列表連接起來)。 但是,在上面的示例中,待辦事項不是數組,似乎它生成了一個對象。 因此,對我來說{... todo}等於{todo}。
另外,在組件上分配了什么樣的屬性?
...
也可以用於散布對象,而不僅僅是數組。 例如,
// Using rest syntax here
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }
// Using spread here
let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }
在上述情況下, todos
是一個對象數組,其中包含completed
鍵和text
。 而不是像這樣手動傳遞道具-
const TodoList = ({ todos, onTodoClick }) => (
<ul>
{todos.map((todo, index) => (
<Todo key={index} completed={todo.completed} text={todo.text} onClick={() => onTodoClick(index)} />
))}
</ul>
)
我們使用傳播語法將鍵值對添加為道具。 您可以將其視為語法糖。
... todo用於將道具傳遞給Todo component。 在Todo原型中,您可以看到有兩個可變類型的原型。 所以...運算符將其傳播(傳遞)到Todo組件的props
const obj = {a: 1, b: 2, c: 3};
<MyComponent {...obj} />
與<MyComponent a={1} b={2} c={3} />
。 因此,您可以使用spread
運算符...
從對象或數組中取出元素。
在React外部,如果const test={a: 1, b:2 }
,則const x = {test} //es6 feature
類似於const x = {test: test}
。 因此,這與const x = {test: {a: 1, b:2}}
另外, <MyComponent {obj} />
會在React中創建錯誤,因為在MyComponent
內部,可用於訪問傳遞的obj
的prop名稱是什么? 空無一人。 因此,錯誤。
function MyComponent(props) {
// What is props.? to access obj
}
因此,您使用帶有名稱的道具,
<MyComponent x={obj} />
function MyComponent(props) {
// props.x has obj
// props.x = obj
console.log(props.x);
return <div />
}
但是,傳播算子會自動給出具有對象鍵和值的道具名稱,作為對象的值,如本答案開頭所示。
正如你在你的問題,說const newTodos = [...todos, newItem]
創建新的數組與舊的待辦事項從攤開todos
,並增加了額外newItem
。 如果您沒有傳播todos
,它將創建newTodos = [[todo1, todo2],newItem]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.