0

我正在将rsuitejs用于组件,并且在我正在创建的表单中,我有一个名为MotivationSlider的自定义滑块,它不会在值更改时更新其所在表单中的数据。自定义 Slider 如下所示:

import React, { useState } from 'react';
import { Slider } from 'rsuite';

const MotivationSlider = () => {
  const [motivation, setMotivation] = useState(2);

  return (
    <Slider
      min={0}
      max={4}
      value={motivation}
      graduated
      progress
      className="custom-slider"
      onChange={v => setMotivation(v)}
      renderMark={mark => {
        if ([0, 4].includes(mark)) {
          return <span>{mark === 0 ? 'Not Very' : 'Highly!'}</span>;
        }
        return null;
      }}
    />
  );
};

export default MotivationSlider;

它被包裹在一个自定义字段中,如下所示:

// CustomField.js:
import React from 'react';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'rsuite';

const CustomField = ({ name, message, label, accepter, error, ...props }) => {
  return (
    <FormGroup className={error ? 'has-error' : ''}>
      <ControlLabel>{label} </ControlLabel>
      <FormControl
        name={name}
        accepter={accepter}
        errorMessage={error}
        {...props}
      />
      <HelpBlock>{message}</HelpBlock>
    </FormGroup>
  );
};

export default CustomField;

// FormPage.js:
<CustomField
  accepter={MotivationSlider}
  name="motivation"
/>

当我更改滑块值时,表单数据不会更改,但是如果我将 CustomField 与这样的普通滑块一起使用,则表单值会更改。

<CustomField 
  accepter={Slider} 
  name="motivation" 
  min={0} 
  max={4} 
/>

我在这里做错了什么?

4

1 回答 1

2

表单自定义控件需要实现属性onChange、、valuedefaultValue

import React, { useState } from "react";
import { Slider } from "rsuite";

const MotivationSlider = React.forwardRef((props, ref) => {
  const { value: valueProp, defalutValue, onChange } = props;
  const [motivation, setMotivation] = useState(defalutValue);
  const value = typeof valueProp !== "undefined" ? valueProp : motivation;

  return (
    <Slider
      ref={ref}
      min={0}
      max={4}
      value={value}
      graduated
      progress
      className="custom-slider"
      onChange={(v) => {
        onChange(v);
        setMotivation(v);
      }}
      renderMark={(mark) => {
        if ([0, 4].includes(mark)) {
          return <span>{mark === 0 ? "Not Very" : "Highly!"}</span>;
        }
        return null;
      }}
    />
  );
});

export default MotivationSlider;

于 2020-09-02T02:15:30.593 回答