首页 > 解决方案 > React - 在默认值更改时执行一个函数

问题描述

如果单选按钮值从其默认值更改,我想显示一个保存按钮。假设默认值为“红色”。用户从红色变为绿色 我想显示一个保存按钮。假设用户在保存绿色选项之前再次更改为红色,然后我不想显示它。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

/*  Renders a radio group */
class Radio extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: props.selected
    };
    this.onChange = this.onChange.bind(this);
  }

  onChange(ev) {
    this.setState({ selected: ev.target.value });
    this.props.onChange(ev);
  }

  render() {
    const {
      options, inputClasses, labelClasses, hiddenLabel, name, inline
    } = this.props;
    return (
      <div className={`radio-group ${inline ? 'inline-radio-group' : ''}`}>
        {
          options.map((option) => {
            const {
              id, value, label
            } = option;
            return (
              <div className="radio" key={`${id}`}>
                <input
                  type="radio" id={id} className={`radio-input ${inputClasses}`}
                  name={name} value={value} onChange={this.onChange}
                  checked={this.state.selected === value ? 'checked' : ''}
                />
                <label htmlFor={id} className={`radio-label ${labelClasses} ${hiddenLabel ? 'sr-only' : ''}`} >
                  {label}
                </label>
              </div>);
          })
          }
      </div>
    );
  }
}

Radio.propTypes = {
  options: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    value: PropTypes.oneOfType([PropTypes.bool, PropTypes.string, PropTypes.number]).isRequired,
    label: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
  })).isRequired,

  name: PropTypes.string.isRequired,

  selected: PropTypes.oneOfType([PropTypes.bool, PropTypes.string, PropTypes.number]),

  inputClasses: PropTypes.string,

  labelClasses: PropTypes.string,

  hiddenLabel: PropTypes.bool,

  onChange: PropTypes.func,

  inline: PropTypes.bool
};

Radio.defaultProps = {
  selected: '',
  inputClasses: '',
  labelClasses: '',
  hiddenLabel: false,
  inline: false,
  onChange: () => { }
};

export default Radio;

import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import Radio from '/Radio';

const DOContainer = () => {
  const options = [
    {
      id: 'red',
      label: 'Red',
      value: 'red'
    },
    {
      id: 'green',
      label: 'Green',
      value: 'green'
    }
  ];

  return (
    <Fragment>
      <div className="do-container">
        <h2>choose a color</h2>
        <div>
          <p>color choose</p>
          <Radio
            options={options} name="do" inline
            selected="red"
          />
        </div>
      </div>
    </Fragment>
  );
};

export default DOContainer;

我已经更新了我的 Radio 组件。

标签: javascriptreactjs

解决方案


您可以提供并支持对组件的onChange回调。<Radio />

因此,您<DOContainer />将添加一个处理程序,您将在其中获取selectedRadio 值并将其保持在状态(应将 DOContainer 转换为有状态组件)。拥有selecteddefault值,您可以比较它们并有条件地显示<Button />.

类似的东西将是<DOContainer />渲染方法的实现:

const options = [
  {
    id: 'red',
    label: 'Red',
    value: 'red'
  },
  {
    id: 'green',
    label: 'Green',
    value: 'green'
  }
];

class DOContainer extends Component {
  constructor(props) {
    super(props)

    const initialValue = 'red'

    this.state = {
      // Default value. It will be always the same.
      default: initialValue,
      // What's the Radio value. It will be keep in sync with the selected Radio value.
      // Initially it has the same value as `initivalValue`,
      // but later will be updated by `onRadioChange`.
      selected: initialValue,
    }

    this.onRadioChange = this.onRadioChange.bind(this)
  }

  onRadioChange (selected) {
    this.setState({ selected })
  }

  render() {
    const { selected, default } = this.state

    return (
      <Fragment>
        <div className="do-container">
          <h2>choose a color</h2>
          <div>
            <p>color choose</p>
            <Radio
              options={options} name="do" inline
              selected={selected}
              onChange={this.onRadioChange}
            />

            { selected !== default ? <Button /> : null }
          </div>
        </div>
      </Fragment>
    );
  }
}

推荐阅读