Reactjs 对聪明和愚蠢的组件做出反应
一直致力于React,并希望了解分离智能和非智能组件的最佳实践。下面的示例显示了父控件的状态,但我已经将按钮ui放在了render中,这些控件应该放在子控件中并通过回调实现回父控件,还是太过了?想法……这是我的密码Reactjs 对聪明和愚蠢的组件做出反应,reactjs,ecmascript-6,babeljs,Reactjs,Ecmascript 6,Babeljs,一直致力于React,并希望了解分离智能和非智能组件的最佳实践。下面的示例显示了父控件的状态,但我已经将按钮ui放在了render中,这些控件应该放在子控件中并通过回调实现回父控件,还是太过了?想法……这是我的密码 class Child extends React.Component { constructor(props){ super(props); } render() { return ( <div><p>I said {this
class Child extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div><p>I said {this.props.greeting} {this.props.count} times</p>
</div>
);
}
}
class Parent extends React.Component {
constructor() {
super();
this.state = {
count: 0,
greeting: "Hello"
};
}
sayHello() {
this.setState((prevState, props) => {
return {
count: prevState.count + 1,
greeting: "Hello"
}
}
)};
sayGoodBye() {
this.setState((prevState, props) => {
return {
count: this.count = 1,
greeting: "Goodbye"
}
}
)};
render() {
return (
<div>
<button onClick={() => this.sayHello() }>Say Hello</button>
<button onClick={() => this.sayGoodBye() }>Say Goodbye</button>
<Child count={this.state.count} greeting={this.state.greeting} />
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('app'));
类子级扩展React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
我说了{this.props.greeting}{this.props.count}次
);
}
}
类父类扩展了React.Component{
构造函数(){
超级();
this.state={
计数:0,
问候语:“你好”
};
}
你好{
this.setState((prevState,props)=>{
返回{
计数:prevState.count+1,
问候语:“你好”
}
}
)};
再见{
this.setState((prevState,props)=>{
返回{
count:this.count=1,
问候语:“再见”
}
}
)};
render(){
返回(
这个。sayHello()}>打招呼
这个。说再见()}>说再见
)
}
}
ReactDOM.render(,document.getElementById('app'));
我认为这种情况下的分离效果很好。这些按钮直接涉及到父级的状态,因此仅为它们创建一个子级将是一件过分的事情。通常,“转储”组件仅用于直观地显示数据/状态。有时它们包含按钮之类的元素,但它们所做的唯一一件事就是通知外部世界发生了X事件
子函数也可以是无状态函数:
const Child = ({ greeting, count }) => (
<div>
<p>I said { greeting } { count } times</p>
</div>
);
const Child=({问候语,计数})=>(
我说了{问候}{数}次
);
你可以试着把一个组件变成一个函数。如果你不能,那么它可能不像你想象的那么垃圾:)这可能更适合吗?与其说是代码审查,不如说是最佳实践问题,但我也会把它放在那里,以供任何建议。我认为这是正确的。此外,子组件实际上可能是一个无状态函数。看看我上面的答案。