为什么我们不能在 React 中将布尔值作为道具传递,它总是要求在我的代码中传递字符串 [英] why we cannot pass boolean value as props in React , it always demands string to be passed in my code

查看:58
本文介绍了为什么我们不能在 React 中将布尔值作为道具传递,它总是要求在我的代码中传递字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我已应用 propType 验证,我的编辑器在为 hasvacancy 道具传递布尔值时仍会引发错误.这是我看到的:

<块引用>

错误:'SyntaxError: JSX 值应该是一个表达式或一个引用的 JSX 文本'

我知道我正在为 'hasvacancy' 道具传递一个字符串类型值,但我需要做什么才能通过道具传递布尔值或其他数据类型.

从'react'导入React;从'react-dom'导入{渲染};类 VacancySign 扩展了 React.Component{使成为() {console.log('------------hasvacancy------', this.props.hasvacancy);如果(this.props.hasvacancy){返回(<div><p>空缺</p>

);} 别的 {返回(<div><p>无空缺</p>

);}}}VacancySign.propTypes ={空缺:React.PropTypes.bool.isRequired}渲染(<VacancySign hasvacancy='false'/> ,document.getElementById('root'));

解决方案

您应该将布尔值括在 {} 中:

render( , document.getElementById('root'));

Even though I have applied propType validation, my editor throws an error on when passing boolean value for the hasvacancy prop. Here is what I'm seeing:

Error: 'SyntaxError: JSX value should be either an expression or a quoted JSX text'

I know I am passing a string type value for 'hasvacancy' prop but what do I need to do so I can pass a boolean or other data types via the 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'));

解决方案

You should enclose the boolean value in {}:

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

这篇关于为什么我们不能在 React 中将布尔值作为道具传递,它总是要求在我的代码中传递字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆