React.js组件接口定义的最佳实践是什么?
React组件接口优化问题
我在React.js中编写了一个Foo组件(其参数“接口”仅包含一个text参数,实际代码中有更多参数):
import React from 'react'; export default class Foo extends React.Component { constructor(props){ super(props); } render(){ return <div>{this.props.text}</div>; } }
我曾尝试通过修改属性访问方式优化代码:
import React from 'react'; export default class Foo extends React.Component { constructor(props){ super(props) this._text = props.text } render(){ return <div>{this._text}</div>; } }
这种方式本应带来以下好处:
- 查看构造函数即可快速了解组件支持的属性
- 属性调用代码更简短、可读性更强
但这会破坏属性的更新流程。在父组件中我这样使用Foo:
<Foo text={this.state.parentText}/>
执行
this.setState({parentText: "new text"})
后,Foo中的文本不再更新。因为Foo的构造函数仅执行一次,私有变量this._text不会随属性变化更新。
使用额外私有属性修改参数访问是错误的做法。
核心问题
请问如何在不破坏更新流程的前提下,为组件定义清晰的接口?
我的一些想法
a) 在render(及componentDidUpdate)开头列出所有用到的属性
render(){ const text = this.props.text; return <div>{text}</div>; }
b) 为每个属性创建getter并放在构造函数下方
get _text(){ return this.props.text; }
c) 简化属性访问方式
避免使用类组件,函数组件可直接访问props.text而非this.props.text;或继承自定义组件类,将props传入render:
render_props(props){ ... }
(React为何默认不将this.props作为参数传入render?)
d) 在文档字符串中记录支持的属性
若您了解更优方案/标准/最佳实践,欢迎告知。
曾尝试但失败的方案
我尝试在子组件中使用state,期望父组件状态更新时自动同步:
import React from 'react'; export default class Foo extends React.Component { constructor(props){ super(props) this.state = { text: props.text } } render(){ return <div>{this.state.text}</div>; } }
但这同样破坏了更新流程,this.state仅在初始化时读取props,后续不会自动同步。
相关主题
- 函数组件如何与第三方库交互?
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

