简体   繁体   English

React 中的隐藏输入/文本区域值 onChange setState - 无需用户输入输入

[英]Hidden Input/Textarea value onChange setState in React - without user typing inputs

I need to trigger a function when the value of Hidden input /textArea/TextField changing in React .ReactHidden input /textArea/TextField 的值发生变化时,我需要触发 function Not when the user enter values.不是当用户输入值时。 When dynamically changing the hidden input value trigger a function.当动态改变隐藏输入值时触发 function。

import TextField from "@material-ui/core/TextField";

class RowComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      xx: "",
      salary: 0,
    };
  }

  handleChange = (event) => {
    this.setState({
      xx: event.target.value,
    });
  };

  render() {
    const {
      member: { salary },
    } = this.props;

    console.log(this.state.xx);

    return (
      <TextField
        name="HiddenField"
        type="hidden"
        value={this.state.salary !== 0 ? this.state.salary : salary}
        onChange={this.handleChange}
      />
    );
  }
}

onChange will not trigger here because it will only fire when the user changes the value of the input field (eg, user types in a new character). onChange不会在此处触发,因为它只会在用户更改输入字段的值时触发(例如,用户键入新字符)。

Based on the logic of your app, It looks like the value of TextField will only be controlled by the prop as long as the RowComponent salary state is not equal to 0 (based off of this condition on your TextField : value={this.state.salary?== 0. this.state:salary : salary} ) - and this is evident and is much more clear when you browse the state/props with React Dev Tools.根据您的应用程序的逻辑,只要RowComponent薪水 state 不等于0 ,看起来TextFieldvalue由道具控制(基于您的TextField上的此条件: value={this.state.salary?== 0. this.state:salary : salary} ) - 当您使用 React 开发工具浏览状态/道具时,这一点很明显并且更加清晰。

So, what you can do is compare the previous props & state with the current ones & assess whether or not to update the state xx因此,您可以做的是将之前的道具和 state 与当前道具进行比较,并评估是否更新 state xx

componentDidUpdate(prevProps, prevState) {
  if (prevProps.member.salary !== this.props.member.salary) {
    if (this.state.salary === 0) {
      this.setState(
        {
          xx: this.props.member.salary
        },
        () => {
          console.log("new xx", this.state.xx);
        }
      );
    }
  }

  if (prevState.salary !== this.state.salary) {
    this.setState(
      {
        xx: this.state.salary
      },
      () => {
        console.log("new xx", this.state.xx);
      }
    );
  }
}

编辑 fragrant-sun-eivqq

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

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