source

부울값을 React의 소품으로 전달할 수 없는 이유는 항상 내 코드에 문자열이 전달되어야 하기 때문입니다.

myloves 2023. 3. 4. 15:27

부울값을 React의 소품으로 전달할 수 없는 이유는 항상 내 코드에 문자열이 전달되어야 하기 때문입니다.

propType 검증을 적용했는데도 에디터가 부울 값을 전달할 때 에러가 발생합니다.hasvacancy소품. 여기 보이는 게 있습니다.

오류: 'SyntaxError: JSX 값은 식 또는 따옴표로 묶인 JSX 텍스트여야 합니다.'

'hasvacancy' 프로포트의 문자열 유형 값을 전달하고 있지만 프로포트를 통해 부울 또는 기타 데이터 유형을 전달하려면 어떻게 해야 합니까?

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'));

{}에는 부울 값을 묶어야 합니다.

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

원래 답변(값 생략)이 더 이상 베스트 프랙티스로 간주되지 않기 때문에 이 답변을 업데이트합니다.다른 컴포넌트 속성값과 마찬가지로 값을 중괄호로 묶기만 하면 됩니다.이 대신 (이것이) 작동합니다.

render(<VacancySign hasVacancy />, document.getElementById('root'));

다음을 수행합니다.

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

이전 구문을 사용하는 경우 propTypes를 업데이트하여 hasVacancy가 필요하지 않도록 하십시오.그렇지 않은 경우 를 사용하여 자유롭게 제한할 수 있습니다.isRequired:

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 } />

언급URL : https://stackoverflow.com/questions/39326300/why-we-cannot-pass-boolean-value-as-props-in-react-it-always-demands-string-to