【问题标题】:How to show html filter/map array with Onclick in React如何在 React 中使用 Onclick 显示 html 过滤器/映射数组
【发布时间】:2021-05-19 20:07:30
【问题描述】:
我试图通过 React 中的 onClick 事件显示过滤后的数组。我希望 li 标签仅在单击按钮时显示。我没有收到任何错误消息,但单击按钮时没有填充任何内容
基本上我想用过滤后的结果呈现我的 li 标签,并在单击按钮时将其显示在我的页面上
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;
有什么想法吗?
【问题讨论】:
标签:
javascript
arrays
reactjs
dictionary
filter
【解决方案1】:
首先,我们需要跟踪按钮是否被点击(我们可以使用状态属性来跟踪它,例如点击)
其次,我们还需要在渲染中返回 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;
【解决方案2】:
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>
);
}```