我们在使用反应时遇到了一些问题,但有点可以归结为我们如何使用反应的一部分。
我们应该如何显示/隐藏子组件?
这就是我们编码的方式(这只是我们组件的片段)......
$finaluserscore = '%4$f';
if ($finaluserscore == 0.00)
{
$finaluserscore = 1.00;
} else {
$finaluserscore = '%4$f';
}
$query = sprintf('UPDATE #__ariquizstatisticsinfo SET Status = %1$s,EndDate = %2$s,MaxScore = %3$f,UserScore = ' . $finaluserscore . ',UserScorePercent = %7$f, Passed = %5$d, ElapsedTime = UNIX_TIMESTAMP(%2$s) - UNIX_TIMESTAMP(StartDate) + UsedTime WHERE StatisticsInfoId = %6$d',
$db->Quote(ARIQUIZ_USERQUIZ_STATUS_COMPLETE),
$db->Quote($finishedDate),
$finishedInfo['MaxScore'],
$finishedInfo['UserScore'],
$finishedInfo['Passed'],
$statisticsInfoId,
$finishedInfo['MaxScore'] > 0 ? min(round(100 * $finishedInfo['UserScore'] / $finishedInfo['MaxScore'], 2), 100.00) : 0.00
);
最近我一直在阅读这样的例子:
_click: function() {
if ($('#add-here').is(':empty'))
React.render(<Child />, $('#add-here')[0]);
else
React.unmountComponentAtNode($('#add-here')[0]);
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
<div id="add-here"></div>
</div>
)
}
我应该使用那个React.render()吗?它似乎会阻止像getInitialState: function () {
return { showChild: false };
},
_click: function() {
this.setState({showChild: !this.state.showChild});
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
{this.state.showChild ? <Child /> : null}
</div>
)
}
这样的各种事情级联到孩子和像shouldComponentUpdate
这样的事情......
答案 0 :(得分:60)
我提供了一个遵循第二种方法的工作示例。更新组件的状态是显示/隐藏子项的首选方法。
鉴于你有这个容器:
<div id="container">
</div>
您可以使用现代Javascript(ES6,第一个示例)或经典JavaScript(ES5,第二个示例)来实现组件逻辑:
Try this demo live on JSFiddle
class Child extends React.Component {
render() {
return (<div>I'm the child</div>);
}
}
class ShowHide extends React.Component {
constructor() {
super();
this.state = {
childVisible: false
}
}
render() {
return (
<div>
<div onClick={() => this.onClick()}>
Parent - click me to show/hide my child
</div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
}
onClick() {
this.setState(prevState => ({ childVisible: !prevState.childVisible }));
}
};
React.render(<ShowHide />, document.getElementById('container'));
Try this demo live on JSFiddle
var Child = React.createClass({
render: function() {
return (<div>I'm the child</div>);
}
});
var ShowHide = React.createClass({
getInitialState: function () {
return { childVisible: false };
},
render: function() {
return (
<div>
<div onClick={this.onClick}>
Parent - click me to show/hide my child
</div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
},
onClick: function() {
this.setState({childVisible: !this.state.childVisible});
}
});
React.render(<ShowHide />, document.body);
答案 1 :(得分:0)
{{1}}