ReactJS中的动态/模块化输入组件

克雷西米尔·切科科(KrešimirČoko)

我只是从React入手,还没有找到解决我的问题的可用解决方案。我偶然发现了有关Redux Form的视频但在我的情况下却不起作用。

我想为表单创建一个动态的“输入”字段,这意味着我有一个组件可以指定其主要是输入还是文本区域(此项目不需要其余部分)

这是我的DashFormInput.js,应该是单个“输入”字段,但我希望它具有动态性,因为它能够更改其输出的html元素以及道具。

var DashFormInput = React.createClass({
getInitialState: function() {
    return {
        value: '',
        actionType: '',
        placeholder: '',
        name: '',
        type: ''
    }
},
handleChange: function(event) {
    this.setState({value: event.target.value});
},
render: function() {
    return (
        <input
            actionType={this.props.actionType}
            onChange={this.handleChange}
            placeholder={this.props.placeholder}
            name={this.props.name}
        />
    );
}
});

这是我的DashboardForm.js,它是我要在其中调用DashFormInput组件的父组件。

var DashboardForm = React.createClass({
    handleSubmit(event) {
    console.log(event);
    event.preventDefault();
    console.log("Form submitted");
},
render: function() {
    return (
        <form
            onSubmit={this.handleSubmit}
            id="dashboardForm" className="half-section">

            <DashFormInput
                type={'text'}
                name={'address'}
                placeholder={'address'}
                className={'dashInput subsection'} />
        </form>
    )
}
});

我正在寻找一个简单的解决方案,不需要任何花哨的东西,但是如果使用标准React Ecosystem无法做到这一点,我将以老式的方式进行。

提前致谢。

罗希特·辛格·森加(Rohit Singh Sengar)

修改您的DashFormInput.js渲染方法,例如

render: function() {
    if(this.props.type=="text"){
        return (
            <input
                actionType={this.props.actionType}
                onChange={this.handleChange}
                placeholder={this.props.placeholder}
                name={this.props.name}
            />
        );
    }
    if(this.props.type=="textarea"){
        return (
            <textarea rows="4" cols="50"
                actionType={this.props.actionType}
                onChange={this.handleChange}
                placeholder={this.props.placeholder}
                name={this.props.name}
            ></textarea>
        );
    }else{
        return <div>No input type defined</div>;
    }
}

现在,从DashboardForm.js中,您可以将DashFormInput组件的类型prop更改为“ text”或“ textarea”,因此您将拥有输入框或textarea。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章