3 回答

TA貢獻1828條經驗 獲得超3個贊
這叫展開語法,屬于es6的新語法,可以在函數調用、數組構造、構造字面量對象時, 將數據展開賦值。
JSX中用在組件屬性上可以將對象的屬性展開到組件上,傳遞給組件props
1、函數調用,展開數組參數
12345 | function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; sum(...numbers); |
2、構造數組,展開數組
12 | const arr1 = [3,4,5]; const arr2 = [0, 1, 2, ...arr1]; // [0,1,2,3,4,5] |
3、構造數組,展開字符串
12 | const str = 'abc' ; const arr = [...str]; // ['a', 'b', 'c'] |
4、構造對象,展開對象
1234 | const obj1 = {a: 1, b: 2, c: 3}; const obj2 = {...obj1, d: 4}; // {a: 1, b: 2, c: 3, d: 4} const obj3 = {...obj1, c: 4}; // {a: 1, b: 2, c: 4} const obj4 = {c: 4, ...obj1}; // {a: 1, b: 2, c: 3} |
5、JSX組件屬性展開
1234567891011 | render(){ const settings = { value: 1, placeholder: '輸入數值' }; return < MyInput {...settings}/> // 上面的寫法類似于 // return < MyInput // value={settings.value} // placeholder={settings.placeholder}/> } |

TA貢獻1794條經驗 獲得超7個贊
你可以在子組件添加一個componentWillRecieveProps周期,在里面獲取到即將接收的props。如下: componentWillReceiveProps(nextProps) { this.setState({ A: nextProps.A }); }

TA貢獻1799條經驗 獲得超9個贊
這叫展開語法,屬于es6的新語法,可以在函數調用、數組構造、構造字面量對象時, 將數據展開賦值。
JSX中用在組件屬性上可以將對象的屬性展開到組件上,傳遞給組件props
1、函數調用,展開數組參數
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers);
2、構造數組,展開數組
const arr1 = [3,4,5];
const arr2 = [0, 1, 2, ...arr1]; // [0,1,2,3,4,5]
3、構造數組,展開字符串
const str = 'abc';
const arr = [...str]; // ['a', 'b', 'c']
4、構造對象,展開對象
const obj1 = {a: 1, b: 2, c: 3};
const obj2 = {...obj1, d: 4}; // {a: 1, b: 2, c: 3, d: 4}
const obj3 = {...obj1, c: 4}; // {a: 1, b: 2, c: 4}
const obj4 = {c: 4, ...obj1}; // {a: 1, b: 2, c: 3}
5、JSX組件屬性展開
render(){
const settings = {
value: 1,
placeholder: '輸入數值'
};
return <MyInput {...settings}/>
// 上面的寫法類似于
// return <MyInput
// value={settings.value}
// placeholder={settings.placeholder}/>
}
添加回答
舉報