我已经在Reactjs中编写了以下代码,以显示来自名为from googletrans import Translator
translator = Translator()
with open('text.txt', 'r') as fin:
text = fin.read()
lst = text.split("\n")
with open('spreadsheet.csv', 'w', encoding= 'UTF-8', newline='') as fout:
headers = "English, Arabic, Chinese(simplified), Chinese(traditional, Finnish, French, German, Greek, Hebrew, Hindi, Irish, Italian, Japanese, Korean, Polish, Portuguese, Russian, Spanish, Turkish\n"
fout.write(headers)
language_lst = ['en','ar','zh-CN', 'zh-TW', 'fi', 'fr', 'de','el', 'iw', 'hi', 'ga', 'it', 'ja', 'ko', 'pl', 'pt', 'ru', 'es', 'tr']
new_lst = []
for item in lst:
for i in language_lst:
translated_text = translator.translate(item, dest = i)
new = str(translated_text).split(",")[2].replace("text=","").strip()
new_lst.append(new)
counter = 0
for z in new_lst:
z.encode('utf-8')
fout.write(z+ ',')
counter += 1
print(z)
if counter % 19 == 0:
fout.write('\n')
的文件中名为“ data”的数组中的元素列表。我试图使显示的按钮可单击,然后在控制台上显示消息"regionData"
,但我不断收到错误消息:
TypeError:无法读取未定义的属性'showSubstation'。
"Button Clicked"
答案 0 :(得分:0)
您正在将普通函数传递给map
,该函数将在没有上下文的情况下被调用,因此具有未定义的this
。
render() {
return (
<ul>
{regionData.data.map(function(name, i){ // <-- this function has undefined this
//which is in turn captured by the arrow function that is created inside:
return <tr><button onClick={ () => {this.showSubstation}}>{regionData.data[i].name}</button></tr>
})}
</ul>
);
}
一种解决方案是将this
作为第二个参数传递给map
,然后将其传递给回调。另一个方法是也将箭头函数用作map
的参数,该函数具有词法,因此保留适当的上下文。
要注意的另一件事是this.showSubstation.bind(this)
是无用的。 showSubStation
是一个箭头函数,无论如何,它们都将忽略绑定的this
并按词法获得this
。
答案 1 :(得分:0)
问题在于您的组件上下文(this
)在map
调用中未公开给您的函数。您应该改用arrow function
,如下所示:
render(){
return (
<ul>
{regionData.data.map((name, i)=>{
return <tr>
<button onClick={ () => {this.showSubstation}}>
{regionData.data[i].name}
</button>
</tr>
})}
</ul>
);
}