React类如何在同一文件中的所有方法中传递变量
问题描述:
我在理解概念时遇到了问题。我想从renderWeather()内部传递windColor变量到render()和函数alertKitesurf我应该使用this.state和setState,或者我可以用变量来完成它吗?React类如何在同一文件中的所有方法中传递变量
我的代码不起作用。
PS。为什么在课堂外你需要添加函数method(),而在类的括号内却不需要?
import React, ....
class WeatherList extends Component { constructor(props) {
super(props);
this.fixit = 'blue'; } // render single city
renderWeather(cityData) {
const lol = this;
const name = cityData.city.name;
const temp = cityData.list.map(weather => (weather.main.temp - 272));
const humi = cityData.list.map(weather => weather.main.humidity);
const wind = cityData.list.map(weather => weather.wind.speed);
// Kitesurf alert!
console.log(lol.fixit);
const windColor = alertKitesurf(wind);
lol.fixit = windColor;
return (
<tr key={name}>
<td className="col-md-3">{name}</td>
<Chart data={temp} color="blue" />
<Chart data={humi} color="blue" />
<Chart data={wind} color={windColor} />
</tr>
); }
render() {
let fixdiv;
if (this.fixit === 'blue') {
fixdiv = <div>test</div>;
}
else {
fixdiv = <div>OMG</div>;
}
return (
<div>
<table className="table table-hover">
<thead>
<tr>
<th className="col-md-3">City</th>
<th className="col-md-3">Temperature</th>
<th className="col-md-3">Humidity</th>
<th className="col-md-3">Wind Speed</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
{fixdiv}
</div>
); } } // function(state) -> function({weather}) -> weather : weather -> weather function mapStateToProps({ weather }) { return { weather }; }
function alertKitesurf(wind) { let color = 'blue'; for (let windspeed of wind) {
if (windspeed > 7) {
color = 'red';
} } if (color === 'red') {
alert("WIND SPOTTED! (14+knots) LETS GO KITSURF!"); } return color; }
export default connect(mapStateToProps)(WeatherList);
答
可以使用的状态。
让探险家这一段时间。
在你的构造函数传递
constructor(props) {
super(props)
this.state = {
windColor: 'blue'
}
}
那么这个类的任何方法中(包括渲染方法),你把它称为this.state.windColor
。
即使您将它作为参数传递,您也需要将其作为somefunc(this.state.windColor)
传递给它。
欲了解更多信息,请参阅本:In a react class: How do I pass a variable inside same component
和关于你的最后一个问题。
如果你的意思
为什么写类&外function关键字没有内部类中的函数关键字。
那么这是更多的JavaScript语法转换。我认为你可以编写函数关键字。
考虑使用箭头函数的这种新方法,并绑定了this
关键字。
class Awesomeness extends Component {
constructor(props) {
super(props)
}
some =() => {
console.log('something wild while this is bound to the class\'s this!')
}
render() {
return <div> You are awesome! </div>
}
}
更多关于此阅读这篇文章真棒:React Binding Patterns: 5 Approaches for Handling this
或者你可以轻松地将其理解为这一点。
//This
const obj = {
a: 1,
b() {
console.log(this.a)
}
}
//Equals this
const obj = {
a: 1,
b: function() {
console.log(this.a)
}
}
可以格式化代码? – udnisap
您可以在变量之前使用'this'关键字使其成为全局特定的类。如果你的变量正在改变渲染函数,那么你应该把它放在状态中,并用setState方法改变它的值。 –