>我有一个显示配方的反应组件。此组件可用于仅查看数据以及编辑数据,具体取决于传递它的"编辑"道具。
目前,我有一些条件逻辑,它将隐藏/显示某些元素,具体取决于用户是要编辑还是查看食谱。这是我的渲染函数:
render() {
let buttons = null;
if (this.props.edit === 'true') {
buttons = <div className="buttonList">
<button onClick={this.onSave} className='defaultBtn'>Save</button>
<button onClick={this.goBack} className='defaultBtn'>Discard Changes</button>
</div>;
} else {
buttons = <div className="buttonList">
<button onClick={this.goBack} className='defaultBtn'>Back</button>
</div>;
}
return (
<div className="single">
<img src={this.state.recipe.imageURL} />
<div className='recipeDetails'>
<h1>{this.state.recipe.name}</h1>
{this.props.edit === 'true' > 0 &&
<TextField type='text' floatingLabelText='Image URL' onChange={this.onImageUrlChange}></TextField>
}
<IngredientList onIngredientChange={this.onIngredientChange}
onDelete={this.onDelete}
ingredients={this.state.recipe.ingredients}
edit={this.props.edit}
addIngredient={this.addIngredient} />
{buttons}
</div>
</div>
);
}
这是实现这一目标的最佳方法吗?使用这样的 if 语句对我来说感觉不对。我觉得我应该有一个ViewRecipe组件和一个EditRecipe组件,它们共享大部分代码,但有一些逻辑来隐藏和显示相关元素。是否有某种反应模式来做到这一点?我已经阅读了一些关于高阶组件的信息,但不确定它们是否适合这个特定问题。
我是否过于复杂了?我应该只有两个单独的组件吗?编辑方面的大部分逻辑。
-
您的道具命名需要审核:
🤔
props.edit ='true'
可以props.mode = 'edit' or 'view'
-
缓解条件逻辑(如果...else(
render
方法,并将其分解为以"render"为前缀的方法。 -
解决方案将是:
renderButtons() { if (this.props.mode === 'edit') return ( <div className="buttonList"> <button onClick={this.onSave} className='defaultBtn'>Save</button> <button onClick={this.goBack} className='defaultBtn'>Discard Changes</button> </div> ) else { return ( <div className="buttonList"> <button onClick={this.goBack} className='defaultBtn'>Back</button> </div> ) } } renderTextField() { if (this.props.mode != 'edit') return null; return ( <TextField type='text' floatingLabelText='Image URL' onChange={this.onImageUrlChange}></TextField> ) } render() { return ( <div className="single"> <img src={this.state.recipe.imageURL} /> <div className='recipeDetails'> <h1>{this.state.recipe.name}</h1> {this.renderTextField()} <IngredientList onIngredientChange={this.onIngredientChange} onDelete={this.onDelete} ingredients={this.state.recipe.ingredients} edit={this.props.edit} addIngredient={this.addIngredient} /> {this.renderButtons()} </div> </div> ); }