reactjs - 如何在 ReactJs 中的 onClick 事件上回调函数
问题描述
我有一个必须handleClick
通过单击renderDetail
函数在{this.state.ShowInfo[i]}
div 中运行的事件。我按照下面的代码进行操作:我使用了回调但没有工作。
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data: [],
ShowInfo: {},
}
}
render() {
const { data } = this.state
const renderInfo = data.map((item, i) => {
return (
<div class="item">
<div onClick={e => this.handleClick(e, item, i)}>
<span>Click</span>
</div>
<div>{this.state.ShowInfo[i]}</div>
</div>
)
})
return <div>{renderInfo}</div>
}
handleClick = (e, element, i) => {
fetch('/json.bc', {///I can see that the json.bc is loaded in network tab by result/////
method: 'POST',
})
.then(response => response.text())
.then(text => {
let Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(prevState => ({
ShowInfo: {
...prevState.ShowInfo, [i]: (Maindata, i) => {
console.log(Maindata)// console.log(Maindata) did not show anything.There is no result in this part////
let element = Maindata
let lenfamilies = element.families.length
console.log(lenfamilies)//// console.log(lenfamilies) did not show anything.There is no result in this part////
let indents = [];
for (let j = 0; j < lenfamilies; j++) {
let numF = i
let numS = j
let stingF = numF.toString()
let stingS = numS.toString()
index = stingF + stingS
indents.push(
<div>
<span
key={index}>
</span>
</div>
)
}
return (
indents
)
}
},
}))
}).catch(error => console.error(error))
}
}
ReactDOM.render(<App />, document.getElementById("Result"))
<div>{this.state.ShowInfo[i]}</div>
使用回调为空。您还有其他方法可以在事件中调用renderDetail
函数吗?handleClick
编辑:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data: [],
ShowInfo: {},
text: {}
}
}
render() {
const { data } = this.state
const renderInfo = data.map((item, i) => {
return (
<div class="item">
<div onClick={e => this.handleClick(e, item, i)}>
<span>Click</span>
</div>
<div>{this.state.ShowInfo[i]}</div>
</div>
)
})
return <div>{renderInfo}</div>
}
handleClick = (e, element, i) => {
fetch('/json.bc', {
method: 'POST',
},)
.then(response => response.text())
.then(text => {
let Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(prevState => ({
ShowInfo: { ...prevState.ShowInfo,[i]: this.renderDetail(Maindata, i)},
}))
}).catch(error => console.error(error))
}
renderDetail(element, i) {
let lenfamilies = element.families.length
let indents = []
let index = 0
for (let j = 0; j < lenfamilies; j++) {
let numF = i
let numS = j
let stingF = numF.toString()
let stingS = numS.toString()
index = stingF + stingS
indents.push(
<div>
<span
key={index}
onClick={e => this.handleText(e, element.families[j], index)}
>
Click
</span>
<span key={index}>
{this.state.text[index]}
</span>
</div>
)
}
return(
indents
)
}
handleText = (e, element, index) => {
this.setState(prevState => ({
text: { ...prevState.text, [index]: "test" }////In this part 'test' should be set in span but it is not been set
}))
}
}
解决方案
因为它{this.state.ShowInfo[i]}
是一个函数,并且要执行它的主体,您需要使用()
函数名称来调用它。
也不要忘记在调用它之前添加一个检查,因为初始值this.state.ShowInfo[i]
将是未定义的,它会抛出错误()
。
()
像这样写[注意ShowInfo[i]
]:
const renderInfo = data.map((item, i) => {
return (
<div class="item">
<div onClick={e => this.handleClick(e, item, i)}>
<span>Click</span>
</div>
{this.state.ShowInfo[i] && <div>{this.state.ShowInfo[i]()}</div>}
</div>
)
})
建议:与其将函数存储在状态变量中,不如只存储数据并编写一个通用方法,该方法将返回每个键的 jsx 部分。
检查这个片段:
function print() {
console.log('body of print method');
}
// it will print the function body
console.log(print);
// it will execute the function body
console.log(print());
完整代码:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data: [],
showInfoData: {},
text: {},
}
}
handleClick = (e, element, i) => {
fetch('/json.bc', {
method: 'POST',
})
.then(response => response.text())
.then(text => {
let Maindata = JSON.parse(text.replace(/\'/g, '"'));
this.setState(prevState => ({
showInfoData: {
...prevState.showInfoData,
[i]: Maindata,
}
}))
})
.catch(error => console.error(error))
}
showInfo(i) {
let element = this.state.showInfoData[i];
if(!element) return null;
let lenfamilies = element.families.length
let indents = [];
for (let j = 0; j < lenfamilies; j++) {
let numF = i
let numS = j
let stingF = numF.toString()
let stingS = numS.toString()
index = stingF + stingS
indents.push(
<div>
<span
key={index}
onClick={e => this.handleText(e, element.families[j], index)}
>
Click
</span>
<span key={index}>
{this.state.text[index]}
</span>
</div>
)
}
return (indents);
}
handleText = (e, text, i) => {
this.setState(prevState => ({
text: { ...prevState.text, [i]: text}
}))
}
render() {
const { data } = this.state
const renderInfo = data.map((item, i) => {
return (
<div class="item">
<div onClick={e => this.handleClick(e, item, i)}>
<span>Click</span>
</div>
<div>{this.showInfo(i)}</div>
</div>
)
})
return <div>{renderInfo}</div>
}
}
推荐阅读
- probability - 使用 Google AutoML 表进行概率(置信度)估计
- javascript - 如果我在 for 循环中调用包含 for 循环的函数,那是 O(n^2) 时间还是 O(n)?
- r - 了解 dplyr 和 group_by
- oracle - ORA-01841 在 where 子句中应用日期条件时出错
- reactjs - 是否可以在 React 中将 React 组件作为 backgroundImage url 提供?
- react-native - 单击深层链接时防止 react-native-webview 打开另一个应用程序
- continuous-integration - GitHub Actions 在推送到所有分支时运行
- django - UnboundLocalError at /Tag/HTC-Phones/ 分配前引用的局部变量'tag' - Django
- java - 为什么 readLine!=null 时读取的 BufferedReader 不起作用?
- php - {Laravel} 如何显示徽章到达消息?qcod/laravel-gamify