根据这个 babel文档,使用ES6 +与React的正确方法是初始组件,如下所示:
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
state = {
loopsRemaining: this.props.maxLoops,
}
}
Run Code Online (Sandbox Code Playgroud)
但是一些官方的例子,比如Dan Abramov自己的React DnD模块,使用ES6 +,但仍然在构造函数中定义状态:
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
// state stuff
}
}
Run Code Online (Sandbox Code Playgroud)
现在,作为React的重要贡献者的Dan Abramov可能知道他可以在构造函数之外定义状态,但仍然选择在构造函数中执行它.
所以我只是想知道哪种方式更好,为什么?
import React, { Component } from 'react';
class Counter extends Component {
state = { value: 0 };
increment = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
decrement = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
通常我看到的是人们在构造函数中执行this.state,如果他使用es6类.如果他不是,他可能使用getinitialstate函数放置状态.但是上面的代码(是的,它是一个工作代码),没有使用这两个.我有2个问题,这里的状态是什么?是一个局部变量?如果是,为什么它没有const?prevState来自哪里?为什么在setState中使用箭头函数?这不是很容易this.setState({value:'something'})吗?
我正在重构一个基于es6类的React组件,该组件使用普通的构造函数,然后绑定方法,并在该构造函数中定义状态/属性.像这样的东西:
class MySpecialComponent extends React.Component {
constructor(props) {
super(props)
this.state = { thing: true }
this.myMethod = this.myMethod.bind(this)
this.myAttribute = { amazing: false }
}
myMethod(e) {
this.setState({ thing: e.target.value })
}
}
Run Code Online (Sandbox Code Playgroud)
我想重构这个,以便我自动绑定函数,并使用属性初始化器的状态和属性.现在我的代码看起来像这样:
class MySpecialComponent extends React.Component {
state = { thing: true }
myAttribute = { amazing: false }
myMethod = (e) => {
this.setState({ thing: e.target.value })
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,我还需要构造函数吗?或道具也是autobound?我本来希望仍然需要构造函数和包含super(props),但我的代码似乎工作,我很困惑.
谢谢
我总是在组件中使用此表达式:
class Cart extends Component { }
Run Code Online (Sandbox Code Playgroud)
最近,我已经看到很多使用此表达式的代码。
class Cart extends React.Component {
constructor(props) {
super(props);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么?使用构造函数和super的目的是什么?React.Component和Component是否相同?为什么我们在构造函数和super中传递道具?我不是在问什么是super和构造函数,我是在问上面两个代码之间的区别以及使用每个代码的好处?
我在网上检查过,但没有看到任何解释,只是代码示例。
我在 Typescript 中使用 ReactJS。我需要下面的“构造函数”代码吗?没有它它也能正常工作,我查看了转换后的 JavaScript,它似乎无论如何都会自动添加它。
interface myProps {
children?: any;
}
class MyButton extends React.Component<myProps, {}> {
constructor(props: myProps) { //Needed ???
super(props);
}
render() {
return (<div>
<button>
{this.props.children}
</button>
</div>);
} //end render.
} //end class.
Run Code Online (Sandbox Code Playgroud)