Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - 通过参考更改输入值(Changing input value by reference)

So the normal way of handling inputs is to have a state variable for it and change it, like this:

(因此,处理输入的通常方法是为其添加一个状态变量并对其进行更改,如下所示:)

    const [title, setTitle] = useState('');
    <Form.Input
        label="Title"
        value={title}
        onChange={(e, data) => {
            setTitle(data.value);
        }}
    />

The problem comes when there are more complex forms, and where the complete form is in a single variable and inside many different components.

(当存在更复杂的表单,并且完整的表单位于单个变量中并且位于许多不同的组件中时,就会出现问题。)

The way I figured it "works" is to include the object where the value is and the name of the property, that way I can change it (but even then it makes things a bit tricky):

(我认为它“起作用”的方式是包括值所在的对象和属性的名称,这样我就可以对其进行更改(但是即使那样,它仍然有些棘手):)

    <Form.Input
        inline
        label="Subtitle"
        value={item.instructions_data.subtitle}
        onChange={(e, data) => {
            onChange(item.instructions_data, data.value, 'subtitle');
        }}
    />

    // onChange example
    const onChange = (source, value, field) => {
        source[field] = value;
        setItem(item);
    };

This way works, but it is far from elegant and it makes a lot of unnecessary boilerplate.

(这种方法有效,但远非优雅,并且使许多不必要的样板。)

What is the better way of doing this?

(这样做的更好方法是什么?)

Can I somehow get a reference object from event in onChange?

(我能以某种方式从onChange事件中获取参考对象吗?)

Thanks for all the help!

(感谢您的所有帮助!)

  ask by Kladnik translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...