如何在React Reusable Component中实现条件渲染?

时间:2020-10-19 02:30:18

标签: javascript reactjs

我有这个可重用的组件,如果要返回true,我想在其中传递一个值:返回一个按钮,如果该值为false,则不呈现该按钮。我无法弄清楚如何使用可重用组件。我要使用的布尔变量是displayButton,如果为true,则呈现按钮;如果为false,则不呈现按钮。

const Test = ({ name, value, onClick, purchased, displayButton }) => {
  return (
    <div class="cardData">
      <h5>{name}</h5>
      <p>Cost: {value}</p>
//if display button = true, display this button, if false, button is not displayed
      <button
        type="button"
        onClick={onClick}
        class="btn btn-primary"
        value={value}
        name={name}
      >
        Purchase
      </button>
      <h4>{purchased}</h4>
    </div>
  );
};

export default Test;

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

const Test = ({ name, value, onClick, purchased, displayButton }) => {
  return (
    <div class="cardData">
      <h5>{name}</h5>
       <p>Cost: {value}</p>
      {displayButton &&
        <button
          type="button"
          onClick={onClick}
          class="btn btn-primary"
          value={value}
          name={name}
        >
          Purchase
        </button>
      }
      <h4>{purchased}</h4>
    </div>
 );
};

export default Test;

如果displayButton的值为true,它将呈现按钮,否则将呈现

答案 1 :(得分:0)

这将起作用。

const Test = ({ name, value, onClick, purchased, displayButton }) => {
  return (
    <div class="cardData">
      <h5>{name}</h5>
      <p>Cost: {value}</p>
      { displayButton && 
      <button
        type="button"
        onClick={onClick}
        class="btn btn-primary"
        value={value}
        name={name}
      >
        Purchase
      </button>
      }
      <h4>{purchased}</h4>
    </div>
  );
};

export default Test;

答案 2 :(得分:0)

您可以创建一个ShowHide组件,该组件可用于条件渲染,而不必在需要进行条件渲染的每个JSX中使用逻辑运算符。

// create a ShowHide component
const ShowHide = ({show,children} ) => show && children

//  your Test component with the button wrapped in ShowHide
const Test = ({ name, value, onClick, purchased, displayButton }) => {
  return (
    <div class="cardData card col-6 m-3">
      <h5>{name}</h5>
      <p>Cost: {value}</p>
      <ShowHide show={displayButton}>
        <button
          type="button"
          onClick={onClick}
          class="btn btn-primary"
          value={value}
          name={name}
        >
          Purchase
        </button>
      </ShowHide>
      <h4>{purchased}</h4>
    </div>
  );
};

const root = document.getElementById('root');

ReactDOM.render(
  <Test name="My Card"
    value="250,000"
    onClick={() => alert('clicked')} 
    purchased="Yes!" 
    displayButton={false}
  />,
  root
)
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
  

<div id="root"></div>

祝你好运...