gpt4 book ai didi

javascript - ReactJS 与 ReactRedux : Implementing Search to Query List of Items

转载 作者:行者123 更新时间:2023-12-03 01:04:08 27 4
gpt4 key购买 nike

设置一些上下文:我有一个返回键/值对数组的 API。我想添加一个功能,在加载(完成)时在网页上显示每个键/值,并使用文本框在此列表上实现“搜索”,当用户键入时,列表会缩小到仅匹配的键。

相关React代码如下:

var PropEntry = function PropEntry(p) {    
var displayValue = React.createElement(
"span",
null,
p.value
);
var valueMarkup = React.createElement(
"div",
null,
React.createElement(
"span",
{ className: "prop-value" },
displayValue
);
return React.createElement(
"div",
{ className: "prop-entry" },
React.createElement(
"label",
null,
p.name
),
valueMarkup
);
};

var ColsView = function ColsView(props) {
var cols = props.streamCols;
return React.createElement(
"div",
{ className: "named-container" },
React.createElement(
"input",
{ type: "text", placeholder: "Search", onChange: <CallFunctionHere> }),
React.createElement(
"div",
{ className: "named-entries" },
cols.map(function (col) {
return React.createElement(PropEntry, { name: col.Name, value: col.value });
})
)
)
}

ColsView = ReactRedux.connect(function (state) {
return { streamCols: state.streamCols };
})(ColsView);

我正在尝试在列表上方添加一个文本框,用于在用户键入(onChange 击键)时过滤此列表。最好的方法是什么?我想避免再次调用 API,因为我已经有了完整的项目列表。

我还应该提到,我是 React 的初学者,我只是想向现有的 .js 文件添加功能,我不想完全重写:)

最佳答案

你们看起来很接近!

作为类的一部分,定义可用于处理点击的回调:

handleChange = (event) => {
// Get the value from the event
const searchValue = event.target.value;

// Save it to state
this.setState({ searchValue });
}

您应该更新搜索框的定义以从状态中提取其值,以便在组件重新渲染时 React 不会删除该值:

React.createElement(
"input",
{
type: "text",
value: this.state.searchValue;
placeholder: "Search",
// Note that we just pass the function here, we don't actually call it.
// React will call it for us when an onchange event occurs for this element
onChange: this.handleChange,
}
);

现在,在渲染方法中,您可以根据状态中保存的值进行过滤:

const regex = new RegExp(this.state.searchValue);
const filteredCols = Object.keys(cols)
.filter(key => key.match(regex))
.reduce((filtered, key) => {
filtered[key] = cols[key];
return filtered;
}, {});

filteredCols.map(function (col) {
return React.createElement(PropEntry, { name: col.Name, value: col.value });
});

正如我们都指出的,正则表达式可能不会那么简单(现在是完全匹配),但如果需要,可以在另一个问题中处理。

关于javascript - ReactJS 与 ReactRedux : Implementing Search to Query List of Items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52486784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com