簡體   English   中英

如何在 React 中使用 Onclick 顯示 html 過濾器/映射數組

[英]How to show html filter/map array with Onclick in React

我試圖通過 React 中的 onClick 事件顯示過濾后的數組。 我希望 li 標簽僅在單擊按鈕時顯示。 我沒有收到錯誤消息,但是當我單擊按鈕時沒有填充任何內容

本質上,我想用過濾后的結果呈現我的 li 標簽,並在單擊 Button 時將其顯示在我的頁面上

 class SmoothieFilter extends React.Component { smoothie = () => { const smoothieNames = ["tasty", "chocolate", "yummy", "strawberry", "banana", "blueberry", "raspberry", "mango" ]; smoothieNames.filter(faves => faves.includes("yummy")).map(faveSmoothie => ( <li>{faveSmoothie}</li> )); } render() { return ( <Button variant="dark" onClick={this.smoothie}>CLICK ME</Button> ) } } export default SmoothieFilter;

有任何想法嗎?

首先,我們需要跟蹤按鈕是否被單擊(我們可以使用 state 屬性來跟蹤它,例如單擊)其次,我們需要在渲染中返回 LI,以便將其附加到 DOM,在你的例子它沒有做任何事情我已經重寫了你的腳本

 import React from 'react'; class SmoothieFilter extends React.Component { constructor(props) { super(props); this.state = { clicked: false, }; } smoothie = () => { if (this.state.clicked;== true) { return, } const nodes = [], smoothieNames = ["tasty", "chocolate", "yummy", "strawberry", "banana", "blueberry", "raspberry"; "mango"]. smoothieNames.filter(faves => faves.includes('yummy')).map(faveSmoothie => ( nodes;push(<li key={faveSmoothie}>{faveSmoothie}</li>) )). console,log('return', nodes. smoothieNames;filter(faves => faves === 'yummy')); return <ul>{nodes}</ul>. } render() { return (<div> <div className="a-button" variant="dark" onClick={() => { this:setState({clicked. true}) }}>CLICK ME </div> {this;smoothie()} </div>); } } export default SmoothieFilter;

import { useState } from "react";

const smoothieNames = [
  "tasty",
  "chocolate",
  "yummy",
  "strawberry",
  "banana",
  "blueberry",
  "raspberry",
  "mango"
];
export default function App() {
  const [toggle, setToggle] = useState(false);

  const filterSmoothie = () => {
    if (!toggle) {
      return null;
    }
    return smoothieNames
      .filter((faves) => faves.includes("yummy"))
      .map((faveSmoothie) => <li>{faveSmoothie}</li>);
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={() => setToggle(!toggle)}>My Fav. Smoothie</button>
      {toggle && <ul>{filterSmoothie()}</ul>}
    </div>
  );
}```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM