当我传递变量并成功导入需求时。 已传递道具和必需的功能,但无法说明该值 希望通过示例获得适当的指导。
答案 0 :(得分:0)
var React = require('react');
var ReactPropTypes = React.PropTypes;
import React, {Component, PropTypes} from 'react';
var Header = React.createClass({
render: function() {
return (
<header>
<h1>This is the header section</h1>
</header>
);
}
});
module.exports = Header;
export default class Header extends Component {
render() {
return (
<header>
<h1>This is the header section</h1>
</header>
);
}
}
var React = require('react');
var ReactPropTypes = React.PropTypes;
var Header = React.createClass({
propTypes: {
title: ReactPropTypes.string.isRequired
}
});
import React, {Component, PropTypes} from 'react';
export default class Header extends Component {
render() {
return (
<header>
<h1>This is the header section</h1>
</header>
);
}
}
//Note that the propTypes has to be defined outside of the class definition
Header.propTypes = {
title: PropTypes.string.isRequired
}
ES6语法看起来很奇怪,因为propTypes部分位于类定义之外。这是由于在ES6的类中只能定义方法。如果要定义属性,则它们必须在类之外。
为避免此问题,请使用ES7属性初始化器:
import React, {Component, PropTypes} from 'react';
export default class Header extends Component {
// brings the propTypes inside the class definition
// Note that propTypes belongs to the class, and thus it is static
// non-static properties (instance properties) is shown in the next section
static propTypes = {
title: PropTypes.string.isRequired
}
render() {
return (
<header>
<h1>This is the header section</h1>
</header>
);
}
}
var Header = React.createClass({
getInitialState: function() {
return {
title: this.props.title
};
},
});
export default class Header extends Component {
constructor(props) {
/* Note props is passed into the constructor in order to be used */
super(props);
this.state = {
title: props.title
};
}
}
使用ES7的属性初始化程序进一步简化此代码:
export default class Header extends Component {
// instance property
state = {
title: this.props.title
};
// followed by constructor...
}
var Header = React.createClass({
handleClick: function(event) {
this.setState({liked: !this.state.liked});
// Note here that **this** is automatically bind to the component itself
}
});
但是,在ES6中,React团队决定不将其自动绑定到组件。因此,要在ES6中重写上面的代码,我们需要将handleClick函数绑定到构造函数中的组件:
export default class Header extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({liked: !this.state.liked});
}
}
React博客建议使用ES7属性初始化程序:
export default class Header extends Component {
handleClick = (event) => {
this.setState({liked: !this.state.liked});
}
}
handleClick = ...是ES7属性初始化程序语法。 (事件)=> {}是ES6粗箭头语法,在调用时会保留上下文。