React形式失去了对更新的关注

时间:2017-09-06 10:01:49

标签: javascript reactjs

我正在尝试使用通用输入创建一个表单,但每次输入我的输入时,我都会失去此输入的焦点,我必须再次单击它们。

// dummyData.js
const dummyData = [
    {
       title: 'this is a title',
       type: 'book'
    },
    {
       title: 'this is another title',
       type: 'movie'
    },
    {
       title: 'this is a foo',
       type: 'bar'
    }
];
export default dummyData;

// on your component
import dummyData from '/path/to/your/dummyData.js';

1 个答案:

答案 0 :(得分:0)

是不是输入的值需要与onchange结果同步?

考虑一下:

handleChange(propertyName, event) {
    const contact = this.state.contact;
    contact[propertyName] = event.target.value;
    this.setState({ contact: contact });
}

constructor(props) {
    super();
    this.state = {
        contact: props
    }
}

render() {
    const FormInput = (props) => {
        return (
            <label>
                Name:
                <input 
                    type="text" 
                    placeholder="Enter text"
                    onChange={event => this.handleChange(props.name, event)}
                    value={this.state.contact.value}
                />
            </label>
        )
    }

    return (
        <form>
            <FormInput value={this.state.videoName} name="videoName" />
            <FormInput value={this.state.title} name="title" />
        </form>
    );
};

此代码未经测试,但它等同于getInitialState,您可以执行此操作,也可以在handleChange中向父组件添加回调,以更新其在道具中发送的内容