【问题标题】:React Rails Passing props to React SelectReact Rails 将 props 传递给 React Select
【发布时间】:2023-03-08 03:54:01
【问题描述】:

我正在尝试使用 React rails 将我的 Rails 数据库中的道具传递给 React Select 组件,但文本在选择选项中显示为不可见。

查看:

= react_component('SelectSearch', options: Course.all.as_json(only: [:title]))

反应选择组件:

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

class SelectSearch extends React.Component {
  constructor(props) {
      super(props)
    }

  state = {
    selectedOption: null,
  };

  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={this.props.options}
      />
    );
  }
}

export default SelectSearch;

当单击选择中的某些内容时,它会记录控制台日志,例如:

Option selected: {title: "English"}

但是打开选择,它完全是空白的。显然那里有一个可以点击的选项,但没有显示任何内容。同样对于搜索,不显示任何选项。

我知道这是因为我错误地传递了 props,或者错误地处理了数据,我不想要 {title: "English"} 我只想要 English 但不确定如何正确过滤。

【问题讨论】:

  • 在 render() 函数中添加 console.log({ selectedOption, 'this.props.options': this.props.options }) 以供返回。请提供控制台输出。
  • selectedOption: null, this.props.options: Array(2)} selectedOption: null this.props.options: Array(2) 0: {title: "Korean"} 1: {title: "English"} length: 2 __proto__: Array(0) __proto__: Object

标签: javascript ruby-on-rails reactjs


【解决方案1】:

查看 react-select 示例:

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
]

const MyComponent = () => (
  <Select options={options} />
)

您的选项包含不需要的“标题”属性,并且不包含“值”和“标签”。修复它。

【讨论】:

    【解决方案2】:

    我花了一段时间才弄明白,但得到了这个工作:

    = react_component('SelectSearch', data: Course.all.as_json(only: [:title]))
    
    import React from 'react';
    import Select from 'react-select';
    
    class SelectSearch extends React.Component {
      constructor(props) {
        super(props);
      }
    
      state = {
        selectedOption: null,
      };
    
      handleChange = selectedOption => {
        this.setState({ selectedOption });
        console.log(`Option selected:`, selectedOption);
      };
    
      render() {
        const { selectedOption } = this.state;
    
        return (
          <Select
            value={selectedOption}
            onChange={this.handleChange}
            options={this.props.data}
            getOptionLabel={(option) => option.title}
            getOptionValue={(option) => option.title}
          />
        );
      }
    }
    
    export default SelectSearch;
    

    React-select 需要 valuelabel,这似乎是通过它的最简单方法。

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 2021-03-17
      • 2021-09-17
      • 2017-09-14
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2020-04-10
      • 2015-10-30
      相关资源
      最近更新 更多