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

Reactjs 为什么我们不能在React中传递布尔值作为道具,它总是要求在我的代码中传递字符串,reactjs,redux,Reactjs,Redux,尽管我已经应用了propType验证,但我的编辑器在为hasSpacementprop传递布尔值时仍会抛出一个错误。以下是我看到的: 错误: 'SyntaxError:JSX值应为表达式或带引号的JSX文本' 我知道我正在为'HasSpacement'属性传递字符串类型值,但我需要做什么才能通过该属性传递布尔值或其他数据类型 import React from 'react'; import { render } from 'react-dom'; class VacancySign ext

尽管我已经应用了propType验证,但我的编辑器在为
hasSpacement
prop传递布尔值时仍会抛出一个错误。以下是我看到的:

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

我知道我正在为'HasSpacement'属性传递字符串类型值,但我需要做什么才能通过该属性传递布尔值或其他数据类型

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'));
从“React”导入React;
从'react dom'导入{render};
类VacancySign扩展了React.Component{
render(){
console.log('-----------hassubance-----',this.props.hassubance);
如果(本道具有空缺){
返回(
空缺

); }否则{ 返回( 没有空缺

); } } } VacancySign.propTypes={ Has空缺:React.PropTypes.bool.isRequired } 渲染(, document.getElementById('root');
您应该将布尔值括在{}中:

render(<VacancySign hasvacancy={false}/> , document.getElementById('root'));
render(,document.getElementById('root'));

我正在更新这个答案,因为我原来的答案(忽略值)不再被认为是最佳实践。现在,只需像对待任何其他组件属性值一样,将值用大括号括起来。因此,与此相反(这仍然有效):


对于那些收到警告的人

warning.js?6327:33 Warning: Received `true` for a non-boolean attribute `editable`
如果在不取出布尔值的情况下向下传递道具,则会发生这种情况 道具

例如:

const X=props=>props.editable?:
这可以通过

const X = ({ editable, ...props }) => editable ? <input { ...props } /> : <div { ...props } />
const X=({editable,…props})=>editable?:

当我们传递整数值或浮点值时,同样的规则也适用。对???@vishnushekhawa在
中包装的任何内容都将作为字符串发送。如果要保留值类型,例如整数、浮点、布尔值、对象等,则需要将其包装在
{}
.returns
Warning:Received
false`对于非布尔属性
static
`对于meI,我认为最好将defaultProp'hasSpacement'设置为false,只需将属性设置为这样的简短形式就更简洁了这在控制台中显示了一个警告:
Warning.js?6327:33警告:对于非布尔属性,Received`true``可编辑`.
@Tom您的PropType似乎设置不正确。错误消息表示您收到了非布尔属性“可编辑”(坏)的布尔值(好)。请确保您的PropType是React.PropTypes.bool,而不是React.PropTypes.string或其他东西。@Artif3x已经有一段时间了,但我记得在我的例子中,
editable
是一个本机组件的html属性,比如
textarea
,或者我根本没有设置道具类型(在这种情况下,它也不应该是字符串,对吗?)@Tom“editable”属性的类型是String,而不是Boolean。请记住,“editable”可以是“true”、“false”或“inherit”,因此为其指定布尔值将无效。这才是真正的答案。您还可以将true=+true或将true更改为数值,因为JS非常棒,但如果不从道具中取出值,则会出现此错误。谢谢你的解释!
VacancySign.propTypes ={
    hasVacancy: React.PropTypes.bool.isRequired
}
warning.js?6327:33 Warning: Received `true` for a non-boolean attribute `editable`
const X = props => props.editable ? <input { ...props } /> : <div { ...props } />
const X = ({ editable, ...props }) => editable ? <input { ...props } /> : <div { ...props } />