react-select:如何解决“警告:Prop `id` 不匹配”

问题描述 投票:0回答:6

我有一个带有 ReactJs 和 NextJs 的网络应用程序。在功能组件中,我使用了 react-select 然后,我收到以下控制台警告:

警告:道具

id
不匹配。服务器:“react-select-7-input” 客户端:“react-select-2-input”

我的代码如下:

import { Row, Col, Card, Form, Button } from 'react-bootstrap';
import Select from 'react-select';

const priorityOptions = [
  { value: 'p1', label: 'Top level - P1' },
  { value: 'p2', label: 'Mid level - P2' },
  { value: 'p3', label: 'Low level - P3' }
];
const PostView = () => {
  return (
    <div className="DashboardSla-ContentBody__Form">
      <Row>
        <Col md="10">
          <Card className="shadow-sm">
            <Card.Body>
              <Form>
                <h5 className="text-secondary mb-3">Booking details</h5>
                <Form.Group controlId="postType">
                  <Form.Label>Booking priority</Form.Label>
                  <Select 
                    id="postType"
                    placeholder="Make a selection"
                    options={priorityOptions}
                  />
                </Form.Group>
                <Button
                  type="submit"
                  variant="primary"
                >Add Booking</Button>
              </Form>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default PostView;
javascript reactjs next.js react-select
6个回答
163
投票

尝试添加道具

instanceId
设置为唯一字符串并且应该可以工作


39
投票

React 18 引入了一个

useId
钩子,用于生成水合安全(跨客户端和服务器渲染稳定)但仍然全局唯一的 ID。你可以用它来解决这个问题。我使用以下组件代替
Select
:

import React, { useId } from 'react';
import Select from 'react-select';

export default function StableSelect({ ...props }) {
  return <Select {...props} instanceId={useId()} />;
}

您可以像

Select
一样使用这个组件,但它不会引发任何水合错误,因为它的ID是稳定的。


20
投票

选择组件需要instanceId,id必填 所以只需添加

id="长值选择" instanceId="长值选择"

对于您的选择组件,它将删除警告:)


1
投票

Instanceid 应该是 React select 属性中的任何字符串,它肯定会起作用......

instanceId = "select-box"

0
投票
<Select
  className={className}
  name={field.name}
  id="long-value-select"
  instanceId="long-value-select"
  value={getValue()}
  onChange={onChange}
  placeholder={placeholder}
  options={options}
  isMulti={isMulti}
/>

0
投票

如果我将唯一的实例ID添加到选择道具中,问题就解决了

<Select
  instanceId="unique-id"
/>
© www.soinside.com 2019 - 2024. All rights reserved.