最近,我一直在搜索以了解实时搜索输入背后的发展,内容是一个数组。就我而言,该数组用于创建文件树。所有代码都在这里: https : //codesandbox.io/s/815p3k3vkj
经过一些调查和查看一些工作示例后,解决方案看起来很简单,但后来我明白我仍然对它的创建感到困惑。所以,我定义了初始状态,但我对接下来要做什么感到困惑,将搜索与数组连接起来。
所以,我开始做这样的事情:
export class SearchEngine extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
this.inputChange = this.inputChange.bind(this);
}
inputChange(e) {
const content = e.target.value;
this.props.onChange();
}
static defaultProps = {
onChange: (search) => {
}
}
render() {
return (
<input placeholder="Search the tree..." onChange={this.inputChange}/>
);
}
}
export default SearchEngine;
这是数组和<FileTree>
:
let data = [
{
type: "directory",
name: ".",
contents: [
{
type: "directory",
name: "./bin",
contents: [{ type: "file", name: "./bin/greet" }]
},
{
type: "directory",
name: "./lib",
contents: [{ type: "file", name: "./lib/greeting.rb" }]
},
{
type: "directory",
name: "./spec",
contents: [
{ type: "file", name: "./spec/01_greeting_spec.rb" },
{ type: "file", name: "./spec/02_cli_spec.rb" },
{ type: "file", name: "./spec/spec_helper.rb" }
]
},
{ type: "file", name: "./CONTRIBUTING.md" },
{ type: "file", name: "./Gemfile" },
{ type: "file", name: "./Gemfile.lock" },
{ type: "file", name: "./LICENSE.md" },
{ type: "file", name: "./README.md" }
]
}
];
export class FileTree extends React.Component {
constructor(props) {
super(props);
this.state = {
activeNode: null
};
this.setActiveNode = this.setActiveNode.bind(this);
}
setActiveNode(name) {
this.setState({ activeNode: name });
this.props.liftStateUp(name);
}
render() {
return (
<div className="padd_top">
{renderTree(
this.props.root || root,
this.setActiveNode,
this.state.activeNode
)}
</div>
);
}
}
export default FileTree;
我很感激在这件事中给出的所有清晰度,我想提前感谢您提供的所有帮助。我是一个 ReactJS 新手并且处于新的理解之中。
谢谢你。
你的问题是你props.onChange
在SearchEngine
类中没有定义的函数。如果你的组件依赖于prop.onChange
一个函数并且你直接调用它,你必须设置所需的道具
import PropTypes from 'prop-types'
class SearchEngine extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired
}
}
或者你可以保护你的组件
class SearchEngine extends React.Component {
static defaultProps = {
onChange: () => {}
}
}
如果 prop 没有通过,它实际上什么都不做,但它不会崩溃。从您的示例中不清楚 onChange 应该做什么,但您没有从index.js
渲染的地方传递它SearchEngine
编辑:工作解决方案https://y7p6zlmpyx.codesandbox.io/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句