我有以下组件:
import React from 'react';
import styles from './ShareModal.css';
import { observer } from 'mobx-react';
// Components
import Modal from '../Modal/Modal';
import Button from '../Button/Button';
import Input from '../Input/Input';
// Stores
import UiStore from '../../stores/UiStore';
@observer
class ShareModal extends React.Component {
constructor () {
super();
this.state = {
inputs : [
{ type: 'email', placeholder: 'Email Address' }
]
};
}
addInput () {
// DEBUG
console.log('Adding an input...');
// this.state.inputs = this.state.inputs.concat([
// { type: 'email', placeholder: 'Email Address' }
// ]);
this.setState(this.state.inputs.concat([
{ type: 'email', placeholder: 'Email Address' }
]));
}
render () {
return (
<div className={ UiStore.state.shareVisible ? styles.visible : styles.hidden }>
<Modal id={'share'}>
<div className={styles.content}>
<h1 className={styles.title}>Share</h1>
<p className={styles.description}>Share with as many friends as you want. Add their email addressess below</p>
{
// Itterates over all inputs in the current state
this.state.inputs.map((item, i) => (
<Input key={i} type={item.type} placeholder={item.placeholder} />
))
}
<Button
icon = {'add'}
color = {'#FC3839'}
type = {'outline'}
text = {'Add Another Email Address'}
width = {'full'}
rounded = {false}
action = {this.addInput.bind(this)}
/>
<Button
color = {'#FC3839'}
type = {'full'}
text = {'Share'}
width = {'full'}
rounded = {true}
/>
</div>
</Modal>
</div>
);
}
}
export default ShareModal;
我坚持使用addInput
功能。你可以收集当该函数运行时应该发生的事情......所以在按钮上单击它运行(它做)然后应该在this.state.inputs
中添加另一个输入,但它似乎不起作用。也没有出现错误。
答案 0 :(得分:3)
我不知道mobx,但不应该是:
this.setState({
inputs: this.state.inputs.concat([
{ type: 'email', placeholder: 'Email Address' }
])
});
答案 1 :(得分:1)
小改变,它会起作用。您需要使用对象设置状态。 Combobox
返回一个数组。
Array.concat
答案 2 :(得分:1)
引自here:
React可以将多个
setState()
个调用批处理为一个更新 性能因为
this.props
和this.state
可以异步更新,所以 不应该依赖它们的值来计算下一个状态。
我更喜欢这样做:
this.setState((prevState) => ({
inputs: prevState.concat([
{ type: 'email', placeholder: 'Email Address' }
])
}));
答案 3 :(得分:0)
this.setState接受传递对象的对象..或