反应选择中的自定义输出

时间:2020-04-23 20:06:45

标签: javascript arrays reactjs react-select

我使用react-select并且是新手。我有一个名为Example的组件

import React from "react";
import Select from "react-select";

class Example extends React.Component {
  state = {
    selectedOption: null
  };

  render() {
    const { onHandleChange, options } = this.props;
    return <Select onChange={onHandleChange} options={options} isMulti />;
  }
}

export default Example;

在另一个文件中,我们有一个功能正常的组件

import React, { useState } from "react";
import Example from "./Example";
import { regionOptions, ageOptions, bordOptions } from "./Options";

export default function UserProfile() {
  const [selectedOption, setSelectedOption] = useState({
    region: "",
    age: "",
    bord: ""
  });

  const handleChange = (key, selectedOption) => {
    setSelectedOption(prev => ({ ...prev, [key]: selectedOption }));
  };
  console.log(Object.values(selectedOption));

  return (
    <div>
      <Example
        id="region"
        onHandleChange={value => handleChange("region", value)}
        selectedOption={selectedOption.region}
        options={regionOptions}
      />
      <Example
        id="age"
        onHandleChange={value => handleChange("age", value)}
        selectedOption={selectedOption.age}
        options={ageOptions}
      />
      <Example
        id="bord"
        onHandleChange={value => handleChange("bord", value)}
        selectedOption={selectedOption.bord}
        options={bordOptions}
      />
    </div>
  );
}

我通过handChange事件在控制台中显示值。 但是,当选择增加,我不能说哪一个属于哪个。

我想要console.log而不是 [Array [n],Array [n],Array [n]]

将显示类似的内容 [地区[n],年龄[n],博德[n]]

您可以在这里看到我的代码 https://codesandbox.io/s/upbeat-night-tqsk7?file=/src/UserProfile.js:0-1040

2 个答案:

答案 0 :(得分:0)

只需使用

console.log(selectedOption);

代替

console.log(Object.values(selectedOption));

答案 1 :(得分:0)

您可以做的是创建一个自定义钩子并进行以下更改。

// custom hook

    function useFormInput(initial) {
      const [value, setValue] = useState(initial);

      const handleOnChange = e => {
        setValue(e);
      };

      return {
        selectedOptions: value,
        onChange: handleOnChange
      };
    }

然后输入代码


export default function UserProfile() {
  const region = useFormInput(""); // return { selectedOption, onChange }
  const age = useFormInput("");
  const bord = useFormInput("");

  // NB {...region}  pass deconstructed return values from custom hook to the component
  return (
    <div>
      <Example id="region" {...region} options={regionOptions} />
      <Example id="age" {...age} options={ageOptions} />
      <Example id="bord" {...bord} options={bordOptions} />
      {JSON.stringify(region.selectedOptions)}
      {JSON.stringify(age.selectedOptions)}
      {JSON.stringify(bord.selectedOptions)}
    </div>
  );
}
// your UI component

  render() {
    const { onChange, options } = this.props;
    return <Select onChange={onChange} options={options} isMulti />;
  }

工作示例

https://codesandbox.io/s/optimistic-napier-fx30b