【发布时间】:2017-04-23 01:09:08
【问题描述】:
对于 React 来说基本上是新手,我对如何在组件之间正确传递状态有点困惑。我已经发现了一个类似的问题React – the right way to pass form element state to sibling/parent elements? 但不知道您能否针对下面的代码给我一个具体的答案。
目前应用的结构包括:
- 父组件 -
App - 2 个孩子:
SearchBar和RecipesList
目标是对我的 Meteor 集合进行异步搜索,并仅显示与搜索词匹配的 recipes。
现在,我只是展示我的 Meteor 收藏中的所有食谱。
我创建了一个名为SearchBar 的有状态组件,它将输入值保存为this.state.term。这个想法是将状态传递给RecipesList,但我不确定这是否是正确的做法。或者,我会让App 处理状态并将其传递给孩子。我相信这是一个很常见的场景,你是怎么做到的?
App
class App extends Component {
render( ) {
return (
<div>
<Navbar/>
<SearchBar/>
<RecipesList/>
</div>
);
}
}
SearchBar
export default class SearchBar extends Component {
constructor( props ) {
super( props );
this.state = {
term: ''
};
}
onInputChange( term ) {
this.setState({ term });
}
render( ) {
return (
<div className=" container-fluid search-bar">
<input value={this.state.term} onChange={event => this.onInputChange(event.target.value.substr( 0, 50 ))}/>
Value: {this.state.term}
</div>
);
}
}
RecipesList
const PER_CLICK = 5;
class RecipesList extends Component {
componentWillMount( ) {
this.click = 1;
}
handleButtonClick( ) {
Meteor.subscribe('recipes', PER_CLICK * ( this.click + 1 ));
this.click++;
}
renderList( ) {
return this.props.recipes.map(recipe => {
return (
<div key={recipe._id} className="thumbnail">
<img src={recipe.image} alt="recipes snapshot"/>
<div className="caption">
<h2 className="text-center">{recipe.recipeName}</h2>
</div>
</div>
);
});
}
render( ) {
return (
<ul className="list-group">
{this.renderList( )}
<div className="container-fluid">
<button onClick={this.handleButtonClick.bind( this )} className="btn btn-default">More</button>
</div>
</ul>
);
}
}
// Create Container and subscribe to `recipes` collection
export default createContainer( ( ) => {
Meteor.subscribe( 'recipes', PER_CLICK );
return {recipes: Recipes.find({ }).fetch( )};
}, RecipesList );
【问题讨论】:
-
使用反应状态钩子查看类似的问题和答案:stackoverflow.com/questions/24147331/…
标签: javascript reactjs meteor