如何在 react-select 中将 props 传递给自定义组件 [英] How to pass props to custom components in react-select

查看:33
本文介绍了如何在 react-select 中将 props 传递给自定义组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义组件作为 react-select 中的输入字段.由于我需要验证,我尝试使用 HTML5 oninvalid(JSX 中的 onInvalid)作为输入标签,并为 oninvalid 设置自定义消息.但是,我无法将消息作为道具传递给我在 select 中设置的组件.下面是我的代码.

I am trying to use a custom component as an input field in react-select. Since I need validation I am trying to use HTML5 oninvalid (onInvalid in JSX) for my input tag and set the custom message for oninvalid. However I am unable to pass the message as a prop to the component that I am setting in select. Below is my code.

输入.js

import React from "react";
import { components } from "react-select";

export default class Input extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log("component mounted");
  }
  setInvalidMessage = event => {
    event.target.setCustomValidity("Custom Message");
  };

  render() {
    if (this.props.isHidden) {
      return <components.Input {...this.props} />;
    }
    return (
      <components.Input
        {...this.props}
        required
        onInvalid={this.setInvalidMessage}
      />
    );
  }
}

example.js

import React from "react";
import Input from "./Input";
import Select from "react-select";
import { colourOptions } from "./docs/data";

const InputBoxWithText = props => {
  return <Input {...props} />;
};

export default () => (
  <form>
    <Select
      closeMenuOnSelect={true}
      components={{ InputBoxWithText }}
      options={colourOptions}
    />
    <input type="submit" />
  </form>
);

如果我在 components 属性中传递 Input,我会在 Input.js 中得到硬编码的消息.如果我通过 InputBoxWithText 我根本看不到 Input 安装.

If I pass Input in components attribute I get the hard coded message in Input.js. If I pass InputBoxWithText I don't see Input mounting at all.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Example from './example';

ReactDOM.render(
<Example />,
document.getElementById('root')
);

这是CodeSandBox.io URL.

如果我做错了什么,谁能告诉我.

Can any one let me know if what am I doing wrong.

推荐答案

我没有解决方案(我也在寻找相同的东西),但是您的示例有多个错误.

I don't have the solution (i'm looking for the same thing as well), but you example has multiple errors.

要加载输入,您必须编写 components={{ Input: InputBoxWithText }},因为 Input 的组件名称不是 InputBoxWithText>.

To load the input you have to write components={{ Input: InputBoxWithText }}, since the component name for Input is not InputBoxWithText.

此外,onInvalid 似乎不是 Input API 的一部分,因此它永远不会触发.您是否尝试使用 <input oninvalid=""/>..?

Also the onInvalid does not seem to be part of the Input API, so it will never trigger. Are you trying to use the <input oninvalid="" />..?

这篇关于如何在 react-select 中将 props 传递给自定义组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆