Reactjs 如何根据用户输入动态设置组件的属性?

Reactjs 如何根据用户输入动态设置组件的属性?,reactjs,Reactjs,通过动态获取用户的输入来设置输入字段或任何组件的属性 我想知道是否有任何方法,我会给用户一个选项,从我要提到的组件列表中选择一个组件,并允许他自定义组件属性。例如,如果用户选择输入组件,他必须能够设置该特定组件的属性,如“必需”、“类型”、“占位符”。在渲染方法中,您可以执行以下操作 render() { // change the name and values base on your user input userInputtedAttribName = "placeho

通过动态获取用户的输入来设置输入字段或任何组件的属性


我想知道是否有任何方法,我会给用户一个选项,从我要提到的组件列表中选择一个组件,并允许他自定义组件属性。例如,如果用户选择输入组件,他必须能够设置该特定组件的属性,如“必需”、“类型”、“占位符”。

在渲染方法中,您可以执行以下操作

render() {

    // change the name and values base on your user input
    userInputtedAttribName = "placeholder";
    userInputtedAttribValue = "the placeholder";

    // the object to contain your user defined attribute name and values    
    const dynamicAttributes = {
        [userInputtedAttribName]: userInputtedAttribValue
    };


    return (
        <div>
            <input type="text" {...dynamicAttributes}></input>
        </div>
    )
}
render(){
//根据用户输入更改名称和值
UserInputedAttribute=“占位符”;
UserInputedAttribute=“占位符”;
//要包含用户定义的属性名称和值的对象
常量动态属性={
[UserInputedAttribName]:UserInputedAttribValue
};
返回(
)
}

扩展操作符,{…dynamicAttributes}将动态构建属性及其值

您可以通过将所需的所有属性作为道具传递给子组件来实现

您还应该使用变更处理程序将它们添加到父组件的状态

每次用户更改某些属性时,状态都应该更新

当状态更新时,新状态将作为道具传递给子组件,并且它将更新

我做了一个简单的输入示例:您可以更改其占位符、minLength和required


可能甚至不是您想要的,但我制作了一个中型原型,可以向您展示如何动态创建
组件(输入、按钮、文本区域)

这就像填写表格一样。从“选择”列表中选择要制作的构件类型。然后在下面的文本框中定义所需的属性。添加完所有属性后,单击Generate渲染自定义组件

沙箱:

工作代码:

import React from "react";
import ReactDOM from "react-dom";
import Input from "./Input";
import Button from "./Button";
import TextArea from "./TextArea";

import "./styles.css";

class ComponentGenerator extends React.Component {
  state = {
    componentInProgress: null,
    customizeMode: false,
    attributeName: "",
    attributeSetting: "",
    boolean: false,
    builtComponents: []
  };

  handleSelection = e => {
    this.setState({
      componentInProgress: { componentType: e.target.value },
      customizeMode: true
    });
  };

  createOptions = () => {
    const { customizeMode, componentInProgress } = this.state;
    return (
      <div>
        <h4>Choose a Component:</h4>
        <select
          onChange={this.handleSelection}
          value={!customizeMode ? "Select" : componentInProgress.componentType}
        >
          <option>Select</option>
          <option>Input</option>
          <option>TextArea</option>
          <option>Button</option>
        </select>
      </div>
    );
  };

  handleOnChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleOnSubmit = e => {
    const {
      attributeName,
      attributeSetting,
      boolean,
      componentInProgress
    } = this.state;
    e.preventDefault();

    let componentCopy = JSON.parse(JSON.stringify(componentInProgress));

    componentCopy.props = {
      ...componentCopy.props,
      [attributeName]: boolean ? boolean : attributeSetting
    };

    this.setState({
      componentInProgress: componentCopy,
      attributeName: "",
      attributeSetting: "",
      boolean: false
    });
  };

  setBoolean = boolean => {
    this.setState({
      boolean: boolean
    });
  };

  generateComponent = () => {
    const { componentInProgress, builtComponents } = this.state;

    this.setState({
      componentInProgress: null,
      customizeMode: false,
      builtComponents: [...builtComponents, componentInProgress]
    });
  };

  defineComponentAttributes = () => {
    const {
      componentInProgress,
      attributeName,
      attributeSetting,
      boolean
    } = this.state;
    return (
      <div>
        <h4>
          Customizing:{" "}
          <span className="highlight">{componentInProgress.componentType}</span>
        </h4>

        {/*Render form */}
        <form onSubmit={this.handleOnSubmit}>
          <label>Attribute: </label>
          <input
            className="form-group"
            onChange={this.handleOnChange}
            value={attributeName}
            name="attributeName"
            placeholder="Choose attribute (type)"
          />
          <label>Definition: </label>
          <input
            className="form-group"
            onChange={this.handleOnChange}
            value={attributeSetting}
            name="attributeSetting"
            placeholder="Define attribute (text)"
          />
          <label>This is a Boolean type: </label>
          <input
            type="radio"
            name="boolean"
            onChange={() => this.setBoolean(true)}
          />
          True
          <input
            type="radio"
            name="boolean"
            checked={boolean === false}
            onChange={() => this.setBoolean(false)}
          />
          False
          <button className="form-group" type="submit">
            Add
          </button>
        </form>

        {/*Create List of attributes */}
        {componentInProgress.props && (
          <div>
            <h4>Defined Attributes:</h4>
            {Object.entries(componentInProgress.props).map(
              ([propName, propValue]) => {
                return (
                  <div key={propName}>
                    <span>{propName}: </span>
                    <span>{propValue + ""}</span>
                  </div>
                );
              }
            )}
          </div>
        )}

        <div>
          <h4>Click to finish and generate:</h4>
          <button onClick={this.generateComponent}>Generate</button>
        </div>
      </div>
    );
  };

  renderComponents = () => {
    const { builtComponents } = this.state;
    return builtComponents.map((component, index) => {
      let renderedComponent = () => {
        switch (component.componentType) {
          case "Input":
            return <Input {...component.props} />;
          case "Button":
            return <Button {...component.props} />;
          case "TextArea":
            return <TextArea {...component.props} />;
          default:
            return null;
        }
      };

      return (
        <div key={index} className="componentSection">
          <h4>{component.componentType}</h4>
          {renderedComponent()}
          <div>
            <p>Attributes: </p>
            {Object.entries(component.props).map(([propName, propValue]) => {
              return (
                <div key={propName}>
                  <span>{propName}: </span>
                  <span>{propValue + ""}</span>
                </div>
              );
            })}
          </div>
        </div>
      );
    });
  };

  render() {
    const { customizeMode } = this.state;
    return (
      <div>
        {this.createOptions()}
        {customizeMode && this.defineComponentAttributes()}
        <div className="components">{this.renderComponents()}</div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ComponentGenerator />, rootElement);
从“React”导入React;
从“react dom”导入react dom;
从“/Input”导入输入;
从“/”按钮导入按钮;
从“/TextArea”导入TextArea;
导入“/styles.css”;
类ComponentGenerator扩展了React.Component{
状态={
ComponentProgress:null,
自定义模式:false,
属性名称:“”,
属性设置:“”,
布尔值:false,
内置组件:[]
};
handleSelection=e=>{
这是我的国家({
ComponentProgress:{componentType:e.target.value},
自定义模式:对
});
};
createOptions=()=>{
const{customizeMode,componentInProgress}=this.state;
返回(
选择一个组件:
挑选
输入
文本域
按钮
);
};
handleOnChange=e=>{
这是我的国家({
[e.target.name]:e.target.value
});
};
handleOnSubmit=e=>{
常数{
属性名称,
属性设置,
布尔,
组件进程
}=本州;
e、 预防默认值();
让componentCopy=JSON.parse(JSON.stringify(componentprogress));
componentCopy.props={
…componentCopy.props,
[属性名称]:布尔值?布尔值:属性设置
};
这是我的国家({
ComponentProgress:componentCopy,
属性名称:“”,
属性设置:“”,
布尔值:false
});
};
setBoolean=boolean=>{
这是我的国家({
布尔值:布尔值
});
};
generateComponent=()=>{
常量{ComponentProgress,builtComponents}=this.state;
这是我的国家({
ComponentProgress:null,
自定义模式:false,
内置组件:[…内置组件,组件进程]
});
};
defineComponentAttributes=()=>{
常数{
组件进程,
属性名称,
属性设置,
布尔值
}=本州;
返回(
自定义:{“}
{ComponentProgress.componentType}
{/*呈现形式*/}
属性:
定义:
这是一种布尔类型:
this.setBoolean(true)}
/>
真的
this.setBoolean(false)}
/>
假的
添加
{/*创建属性列表*/}
{componentInProgress.props&&(
定义的属性:
{Object.entries(componentInProgress.props).map(
([propName,propValue])=>{
返回(
{propName}:
{propValue+“”}
);
}
)}
)}
单击以完成并生成:
生成
);
};
renderComponents=()=>{
const{builcomponents}=this.state;
返回builtComponents.map((组件,索引)=>{
让renderedComponent=()=>{
开关(component.componentType){
案例“输入”:
返回;
案例“按钮”:
返回;
案例“TextArea”:
返回;
违约:
返回null;
}
};
返回(
{component.componentType}
{renderedComponent()}
属性:

{Object.entries(component.props).map([propName,propValue])=>{ 返回( {propName}: {propValue+“”} ); })} ); }); }; render(){ const{customizeMode}=this.state; 返回( {this.createOptions()} {customizeMode&&this.defineComponentAttributes()} {this.renderComponents()} ); } } const rootElement=document.getE