为什么我们不能在Boact中将布尔值作为道具传递,它总是要求在我的代码中传递字符串

Vis*_*wat 54 reactjs redux

即使我已经应用了propType验证,我的编辑器在为hasvacancyprop 传递布尔值时会抛出错误.这是我所看到的:

错误:'SyntaxError:JSX值应该是表达式或带引号的JSX文本'

我知道我正在传递'hasvacancy'prop的字符串类型值,但是我需要做什么,所以我可以通过prop传递布尔值或其他数据类型.

import React from 'react';
import { render } from 'react-dom';


class VacancySign extends React.Component{

  render() {
    console.log('------------hasvacancy------', this.props.hasvacancy);
    if(this.props.hasvacancy) {
      return(
        <div>
          <p>Vacancy</p>
        </div>
      );
    } else {
      return(
        <div>
          <p>No-Vacancy</p>
        </div>);
    }

  }
}

VacancySign.propTypes ={
  hasvacancy: React.PropTypes.bool.isRequired
}

render(<VacancySign hasvacancy='false'/> , 
document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

Jan*_*ang 92

你应该在{}中包含布尔值:

render(<VacancySign hasvacancy={false}/> , document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

  • @VishnuShekhawat包含在```或```中的任何东西都将作为字符串发送.如果你想保留值类型,如整数,浮点数,布尔值,对象等,你需要将它包装在`{ }`. (2认同)
  • 为我返回非警告属性“静态”的“警告:接收到”错误”。 (2认同)

Art*_*f3x 38

不要尝试将布尔值作为属性值传递.相反,只需使用它们的存在或缺少它作为您的布尔值:

render(<VacancySign hasVacancy />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

确保更新propTypes以使hasVacancy不再需要,同时:

VacancySign.propTypes ={
    hasVacancy: React.PropTypes.bool
}
Run Code Online (Sandbox Code Playgroud)

  • 这在控制台中显示警告:```warning.js?6327:33警告:对于非布尔属性`editable````收到`true` (5认同)

Arw*_*ett 6

给收到警告的人

warning.js?6327:33 Warning: Received `true` for a non-boolean attribute `editable`
Run Code Online (Sandbox Code Playgroud)

如果您将 props 向下传递而不从 props 中取出布尔值,就会发生这种情况。

例如:

const X = props => props.editable ? <input { ...props } /> : <div { ...props } />
Run Code Online (Sandbox Code Playgroud)

这可以通过以下方式规避

const X = ({ editable, ...props }) => editable ? <input { ...props } /> : <div { ...props } />
Run Code Online (Sandbox Code Playgroud)