在反应中动态渲染表单

时间:2019-09-21 15:33:08

标签: reactjs forms

我已经编写了基于功能的组件,我正在检查开关箱中的类型,具体取决于我在此处创建表单的类型

const component = (props) => {
    let renderObject = null
    let obj;
    const renderdata = () =>{
        console.log(props);
        obj = Object.keys(props.todoprop).map((todoproprties) =>{
            console.log("here we are looking at the data" , props.todoprop[todoproprties])
            let toDoProprties = props.todoprop[todoproprties]
             switch(props.todoprop[todoproprties].type){
                 case 'text':
                     return <input type="text"  key="1"  value={toDoProprties.value}  name = {toDoProprties.name} onChange={props.handleChange} />
                 case 'date':
                     return  <input type="date" key="2" value={toDoProprties.value}  onChange={props.handleChange}/>
                 default:
                    return <textarea rows="10" key="3" cols="30"  rows="10" cols="30"   value={toDoProprties.value} onChange={props.handleChange}/>

             }

        })
    }


    return (
        <div>
            <h1>Hello from component </h1>
            {renderdata()}
            <div className="card">
             <div className="card-body">
              <div>
              {obj}
              <button type="submit" onClick={props.handleSubmit}>Submit</button>
              </div>
             </div>
             </div>
            {console.log(props)}

        </div>
    );

    }
export default component;

下面是渲染我的组件的容器

class container extends Component {
    state = {
        // how i want my data to look  with  a heading with date proprtey and a description
        heading: '',
        date: '',
        description: '', 
        Todo: {
            heading: { type: "text", value: "", placeholder: 'plese enter heading', name:"heading"},
            date: { type: "date", value: "", placeholder: "plese enter date", name: "date" },
            description: {  value: "PLESE DESIGN A GOOD TODO",  placeholder: 'plese enter description',  name: "description"}
        }
    }

    onChangeHandler = (event) =>{
        console.log(event.value)
        this.setState({
            [event.target.name] : event.target.value
        })
        // this.setState({Todo.heading.value: event.target.value })
    }

    onSubmitHandler = () =>{

        console.log("you have succesfully clicked the handler")
        console.log("you are seeing the state" ,this.state.heading);
        console.log("you are seeing the description", this.state.description)
    }

    render() {
        var dataPassingHandler = () => {
            return (<div>
                <Dynamiccomponent  todoprop={this.state.Todo}   handleChange={this.onChangeHandler}  handleSubmit={this.onSubmitHandler}/>
            </div>
            )
        }

        return (
            <div>
                {dataPassingHandler()}
            </div>
        )
    }
}


export default container;

1)在我的容器中,我正在渲染组件,并将类型传递给容器,并且在检查开关箱时,我正在创建表单

2)我在这里遇到两个问题,第一个是如何传递onChange,

3)其次,如何处理onclick并在容器状态下创建新对象

1 个答案:

答案 0 :(得分:1)

由于您已绑定Todo对象中的值,因此您无法输入

<input type="text"  key="1"  value={toDoProprties.value}  name = {toDoProprties.name} onChange={props.handleChange} />

但是您不会在此处更改Todo对象中的值,

onChangeHandler = (event) =>{
    console.log(event.value)
    this.setState({
       [event.target.name] : event.target.value
    })
    // this.setState({Todo.heading.value: event.target.value })
}

以上更改处理程序仅更改状态变量,该变量在state中直接可用。但是您需要更改Todo对象中的值,您可以这样做,

onChangeHandler = (event) => {
   //let's take name and value in a variable so that it can be accesiable in complex state updation
   let name = event.target.name;
   let value = event.target.value;

   //This is the object from Todo which needs to be updated
   let updatedTodo = this.state.Todo[name];

   //this is the functional setState, which take's previous state value to calculate the next state
   this.setState(prevState => ({
       Todo: { ...prevState.Todo, [name]: {...updatedTodo, value: value} }
   }))
}

现在您的输入已受到完全控制,您可以输入。

此外,您还需要在Dynamiccomponent中进行一些更改。对于更改,您可以将代码与此演示进行比较,

Demo

注意:在此处做一些记录。

  1. 在React中,组件名称应位于PascalCase中。例如,Dynamiccomponent应该是DynamicComponentcontainer应该是Container,依此类推。
  2. 在您创建动态输入的组件中,应为每个输入/文本提供name,以便您的onChange处理程序能够顺利运行。