React 将布尔值传递给组件

Oto*_*man 5 reactjs

我试图将布尔值传递给我的组件,以便它可以根据图像的真假来显示图像,但我不太确定如何继续。

这是代码:

布尔值传递给组件:

<SomeComponent showImage={false}/>
Run Code Online (Sandbox Code Playgroud)

尝试在组件上使用它:

const TheImage = showImage => (

      <div align="center">
        {showImage ? (<img src={ImageIwant} alt="The image i want" width="80%" height="80%" />) : ''}
        <p>Here is the image</p>
      </div>); 
Run Code Online (Sandbox Code Playgroud)

我是新来反应的,我不知道为什么这不起作用。

Aka*_*khe 5

在 showImage 中添加花括号以破坏它

const TheImage = { showImage } => (

      <div align="center">
        {showImage ? (<img src={ImageIwant} alt="The image i want" width="80%" height="80%" />) : ''}
        <p>Here is the image</p>
      </div>);
Run Code Online (Sandbox Code Playgroud)


Jus*_*ode 4

更改您的显示图像组件

const TheImage = showImage => (

  <div align="center">
    {showImage ? (<img src="https://lcsc.academyofmine.com/wp-content/uploads/2017/06/Test-Logo.svg.png" alt="The image i want" width="80%" height="80%" />) : ''}
    <p>Here is the image</p>
  </div>);
Run Code Online (Sandbox Code Playgroud)

const TheImage = prop => (

  <div align="center">
    {prop.showImage ? (<img src="https://lcsc.academyofmine.com/wp-content/uploads/2017/06/Test-Logo.svg.png" alt="The image i want" width="80%" height="80%" />) : ''}
    <p>Here is the image</p>
  </div>);
Run Code Online (Sandbox Code Playgroud)

因为您的组件将 prop 作为对象,所以如果您想访问传递的任何属性,您需要使用prop.yourpropertyname

演示