这是index.jsx的第一个组件
这是包含所有数据的数组。
let details=[{
id:'1',
website: 'amazon',
username:'harry',
password: '1234'
},
{
id:'2',
website: 'flipkart',
username:'nowag',
password: 'gfjh'
},
{
id:'3',
website: 'skype',
username:'king',
password: 'yesyes'
},
{
id:'4',
website: 'facebook',
username:'deep',
password: 'hellohello'
}];
课程应用从这里开始
class App extends React.Component{
constructor(props) {
super(props);
this.state= {
filter: null
};
}
setFilter(filter) {
this.setState({filter: filter})
}
render(){
错误在这里"无法读取属性'过滤'未定义"
let filteredPassword = this.props.details.filter(
(detail) =>{
return detail.website.toLowerCase().indexOf(this.state.search)!= -1;
}
);
return (
<ul>
<Filter onUpdateFilter={this.setFilter} />
{
filteredPassword.map((detail)=>{
return <Detail item={detail} key={detail.id} />
})}
</ul>
)
}
}
export default App;
现在还有另一个组件filter.jsx
class Filter extends React.Component{
constructor(props) {
super();
this.state= {
search:'Search'
};
}
updateSearch(event) {
this.setState({search: event.target.value.substr(0,40)});
//this.props.onUpdateFilter(event.target.value.substr(0,40))
}
render() {
return (
<div>
<input type="text" defaultValue={this.state.search} onchange={this.updateSearch.bind(this)}/>
</div>
)
}
}
这是方式,我试图运行我的过滤器,但它无法正常工作
答案 0 :(得分:1)
如果您未将details
传递给该组件,则需要将this.props.details
替换为details
并替换它,因为setFilter
有错误的上下文
<Filter onUpdateFilter={this.setFilter} />
到此:
<Filter onUpdateFilter={filter => this.setFilter(filter)} />
或绑定在构造函数中:
constructor(props) {
super(props);
this.state= {
filter: null
};
this.setFilter = this.setFilter.bind(this)
}
答案 1 :(得分:1)
这就是你的代码应该是这样的:
class App extends React.Component{
constructor(props) {
super(props);
this.state= {
filter: null
};
this.setFilter = this.setFilter.bind(this);
}
setFilter(filter) {
this.setState({filter: filter})
}
render(){
let filteredPassword = this.props.details.filter(
(detail) =>{
return detail.website.toLowerCase().indexOf(this.state.search)!= -1;
}
);
return (
<ul>
<Filter onUpdateFilter={this.setFilter} />
{
filteredPassword.map((detail)=>{
return <Detail item={detail} key={detail.id} />
})}
</ul>
)
}
}
export default App;
class Filter extends React.Component{
constructor(props) {
super(props);
}
updateSearch(event) {
this.props.onUpdateFilter(event.target.value.substr(0,40))
}
render() {
return (
<div>
<input type="text" defaultValue="Search" onchange={this.updateSearch.bind(this)}/>
</div>
)
}
}