Javascript React TextArea组件-如何在ES6中使用getInititalState()?
我有一个相对简单的代码片段,它是用JSX/ES6编写的Javascript React TextArea组件-如何在ES6中使用getInititalState()?,javascript,reactjs,Javascript,Reactjs,我有一个相对简单的代码片段,它是用JSX/ES6编写的 import React from 'react' class TextArea extends React.Component { constructor(props) { super(props); } render() { return ( <div> <textarea defaultValue={this.props.text}></texta
import React from 'react'
class TextArea extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<textarea defaultValue={this.props.text}></textarea>
<h3>{this.props.text.length}</h3>
</div>
)
}
}
TextArea.propTypes = {
text: React.PropTypes.string
}
export default TextArea;
从“React”导入React
类TextArea扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
{this.props.text.length}
)
}
}
TextArea.propTypes={
文本:React.PropTypes.string
}
导出默认文本区域;
由于该类不是使用React.createClass
生成的,因此尝试添加getInitialState
会导致一个大红色控制台警告:
警告:getInitialState是在纯JavaScript类TextArea上定义的。这仅适用于使用React.createClass创建的类。你的意思是要定义国有资产吗
如何在ES6类中正确使用
getInitialState()
?类内构造函数需要设置state
属性
constructor(props) {
super(props);
this.state = { }
}
类内构造函数需要设置
状态
属性
constructor(props) {
super(props);
this.state = { }
}
对于state,您只需在
构造函数中添加this.state={}
。例如:
constructor (props) {
super(props);
this.state = {
placeHolder: 'Type your stuff here!'
};
}
TextArea.defaultProps = {
placeHolder: this.state.placeHolder
};
对于默认道具,可以使用TextArea.defaultProps
。例如:
constructor (props) {
super(props);
this.state = {
placeHolder: 'Type your stuff here!'
};
}
TextArea.defaultProps = {
placeHolder: this.state.placeHolder
};
这超出了您的类,就像您进行验证检查一样。对于state,您只需在构造函数中添加This.state={}
。例如:
constructor (props) {
super(props);
this.state = {
placeHolder: 'Type your stuff here!'
};
}
TextArea.defaultProps = {
placeHolder: this.state.placeHolder
};
对于默认道具,可以使用TextArea.defaultProps
。例如:
constructor (props) {
super(props);
this.state = {
placeHolder: 'Type your stuff here!'
};
}
TextArea.defaultProps = {
placeHolder: this.state.placeHolder
};
这超出了你的课程范围,就像你进行了验证检查一样。最近,我遇到了这句话:。然后我读了ES6课程:)最近我遇到了这句话:。然后我读了ES6课程:)