我尝试了 React 和 React-typist。
我有一些问题。 然后我传递一个将状态更改为“onTypingDone”的闭包并调用它,但无法正常工作。 我认为这是因为打字员可能不会重新渲染内部组件。 例如下面的代码。下面的代码不能很好地工作。
如何才能正确工作?
import * as React from 'react';
import Typist from 'react-typist';
export interface Props {}
export interface State {
className: string
}
export MyComponents extends React.Component<Props, State> {
constructor(props: Props)
{
super(props);
this.state = { className: "before" };
}
switch() {
this.setState({ className: "after" });
}
render()
{
<Typist onTypingDone={this.switch.bind(this)}>
<div className={this.state.className}>
<p>Hello.</p>
</div>
</Typist>
}
}
最佳答案
当我深入研究代码时发现了真正的问题, 打字员正在停止重新渲染,
this.state.className 指向 MyComponents,
但 Typist 中的内容不会重新渲染,
原因是 Typist 组件内的 shouldComponentUpdate
函数
shouldComponentUpdate(nextProps, nextState) {
if (nextState.textLines.length !== this.state.textLines.length) {
return true;
}
for (let idx = 0; idx < nextState.textLines.length; idx++) {
const line = this.state.textLines[idx];
const nextLine = nextState.textLines[idx];
if (line !== nextLine) {
return true;
}
}
return this.state.isDone !== nextState.isDone;
}
shouldComponentUpdate :
render() will not be invoked if shouldComponentUpdate() returns false.
您可以通过以下方式实现解决方案:
<div className={this.state.className}>
<Typist onTypingDone={this.switch.bind(this)}>
<p>Hello.</p>
</Typist>
</div>
关于reactjs - 我的代码无法更新嵌套组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020781/