简体   繁体   English

在 React Hooks 中使用带有“Set”状态的动态变量?

[英]Using Dynamic Var with `Set` State in React Hooks?

This is a pretty common pattern in React components:这是 React 组件中非常常见的模式:

handleTextFieldChange(event)
{
    const name = event.currentTarget.name;
    this.setState({[name]: event.currentTarget.value})
}

What Javascript syntax could be used to do the same with React hooks?什么 Javascript 语法可以用来对 React 钩子做同样的事情?

ie something possibly along the lines of:即可能是这样的:

handleTextFieldChange(event)
{
    const name = event.currentTarget.name;
    this.set[name](event.currentTarget.value);
}

You could use a single useState with a default value of an object that contains all your input values and update that like you are used to with class components.您可以使用单个useState和一个对象的默认值,该对象包含所有输入值,并像您习惯使用类组件一样更新。

Example例子

 const { useState } = React; function App() { const [state, setState] = useState({ email: "", password: "" }); function onChange(event) { const { name, value } = event.target; setState(prevState => ({ ...prevState, [name]: value })); } return ( <div> <input value={state.email} name="email" onChange={onChange} /> <input value={state.password} name="password" onChange={onChange} /> </div> ); } ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

How about something like this?这样的事情怎么样?

function handleTextFieldChange(mySetFunction, event) {
    const value = event.currentTarget.value;
    mySetFunction(value);
}

<TextField
    placeholder="Email"
    name="passwordResetEmailAddress"
    onChange={(e) => handleTextFieldChange(setPasswordResetEmailAddress, e)}
>
    {passwordResetEmailAddress}
</TextField>

I've tested it and it works.我已经测试过它并且它有效。

class Yup extends React.Component {
  state = {
    first: "",
    second: ""
  };

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

  render() {
    const { first, second } = this.state;
    return (
      <div>
        <p>{first}</p>
        <p>{second}</p>
        <input type="text" name="first" onChange={this.handleTextFieldChange} />
        <input
          type="text"
          name="second"
          onChange={this.handleTextFieldChange}
        />
      </div>
    );
  }
}

same with hook和钩子一样

function Yup() {
  const [{ first, second }, setState] = useState({ first: "", second: "" });

  function handleTextFieldChange({ target: { name, value } }) {
    setState(prevState => ({ ...prevState, [name]: value }));
  }

  return (
    <div>
      <p>{first}</p>
      <p>{second}</p>
      <input type="text" name="first" onChange={handleTextFieldChange} />
      <input type="text" name="second" onChange={handleTextFieldChange} />
    </div>
  );
}

You can dynamically update a state for the target field by receiving an update state function as an argument in onChange function.您可以通过接收更新状态函数作为 onChange 函数中的参数来动态更新目标字段的状态。

Example例子

import React, { useState } from "react";

const App = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const onChangeHandler = (setIdentifierState, event) => {
    setIdentifierState(event.target.value);
  };

  return (
    <div>
      <p>{"Email: " + email}</p>
      <p>{"Password: " + password}</p>
      <input
        type="text"
        placeholder="email"
        onChange={onChangeHandler.bind(this, setEmail)}
      />
      <input
        type="text"
        placeholder="password"
        onChange={onChangeHandler.bind(this, setPassword)}
      />
    </div>
  );
};

export default App;



I recently tackled this same problem while converting my components from classes to functions.我最近在将组件从类转换为函数时解决了同样的问题。 I ended up creating an object that could then point to the separate state hooks:我最终创建了一个可以指向单独状态挂钩的对象:

const textStates = {};
const setTextStates= {};
for (var name of names) {
  let [textState, setTextState] = useState("");
  textStates[name] = textState;
  setTextStates[name] = setTextState;
}

I solved it this way (a slightly more dynamic solution than what @VikR offered)我是这样解决的(比@VikR 提供的解决方案稍微动态一点)

const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [video, setVideo] = useState("");

const handleChange = setter => event => {
    const value = event.target.value;
    //special cases
    if (setter === setVideo) {
        setInvalidVideo(!ReactPlayer.canPlay(value))
    }

    setter(value)
}

Then in my code:然后在我的代码中:

        <TextField fullWidth value={title} type="date"
                   label={t('service.ticket.add.title')}
                   placeholder={t('service.ticket.add.titlePh')}
                   onChange={handleChange(setTitle)} variant="outlined"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM