![](/img/trans.png)
[英]React Hooks: How can I use multiple instances of my useToggle hook on one component?
[英]How can I use a React component on multiple instances on the same page?
我有一个纯HTML页面(非React应用程序的一部分),其中一些文本表示简单的数学计算。 有<span>
元素包含公式,在它们旁边的<span>
元素中包含计算内容。 每个范围用一个通用类( formula
或calculation
以及一个特定类(例如formula-1
和calculation-1
。 请注意,类别中的数字对于关联的公式和计算将始终相同。 这些计算的数量也是动态的。 页面上可能有1个或30个。
我正在使用React组件将calculation
范围替换为button
元素,并且当单击按钮时,它将重新渲染以显示计算值。 下面显示了一些示例HTML和JS。
此解决方案有效,但我的问题是感觉很脏。 我对React还是很陌生,但是JavaScript并不是我的主要语言,但是在我看来,每个计算元素都应该由该组件的一个实例来表示,而不是单个组件循环遍历页面和页面上的所有计算。渲染每个。
所以我的问题是:就应如何使用React而言,以下可行的解决方案是否不正确?如果是,那么通常公认的正确做法是什么?
<span class="formula formula-1" data-calculation="4">2 + 2</span> = <span class="calculation calculation-1>4</span>
<span class="formula formula-2" data-calculation="6">2 + 4</span> = <span class="calculation calculation-2>6</span>
<span class="formula formula-3" data-calculation="22">2 + 20</span> = <span class="calculation calculation-3>22</span>
我创建了一个React组件来代替
import React, {Component} from "react";
import ReactDOM from "react-dom";
class Calculate extends Component {
constructor() {
super();
this.viewSolution = this.viewSolution.bind(this);
this.state = {
calculations: []
};
let formula_elements = document.getElementsByClassName('formula');
for (var i = 0; i < formula_elements.length; i++) {
this.state.calculations[i] = formula_elements[i].getAttribute('data-calculation');
}
}
viewSolution(event) {
this.setState({
clicked: true
});
}
render() {
if (this.state.clicked === true) {
return (
<span>{this.state.calculations[this.props.index]}</span>
);
}
return (
<button className="btn" onClick={this.viewSolution}>View solution</button>
);
}
}
export default Calculate;
const calculation_elements = document.getElementsByClassName('calculation');
for (var i = 0; i < calculation_elements.length; i++) {
ReactDOM.render(<Calculate index={i}/>, calculation_elements[i]);
}
我在下面提供一种解决方案。 我不确定您是否要查看用户输入的方程的解,因为使用输入和onChange函数可以很容易地做到这一点。 无论如何,以下内容基于我所理解的问题。
一些注意事项:
import React, { Component } from 'react';
class Calculate extends Component {
state = {
clicked: false
};
viewSolution = event => this.setState({ clicked: true });
render() {
const { clicked } = this.state;
const { answer, calculation } = this.props;
const element = clicked
? <span> = { answer }</span>
: <button
className='btn'
onClick={ this.viewSolution }>
View solution
</button>;
return <div>
<span>{ calculation }</span>
{ element }
</div>;
}
}
class App extends Component {
render() {
const formulae = {
['2 + 2']: 4,
['2 + 4']: 6,
['2 + 20']: 22
};
return <div>
{
Object.keys(formulae).map((calculation, key) => (
<Calculate
answer={formulae[calculation]}
calculation={calculation}
key={key} />
))
}
</div>
}
}
ReactDOM.render(<App />);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.