[英]document.onkeypress in React
我正在嘗試建立一個偵聽任何按鍵並將其發送POST請求到服務器以獲取一些數據的網頁。 使用返回的數據,我想將其呈現到網頁上。
最初,要獲得按鍵,我有一個HTML文件,並且在標頭中有一個腳本標簽,看起來像這樣:
<script type="text/javascript">
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
console.log(charStr);
var params = {
key: charStr
};
var form = document.createElement("form");
console.log(form);
form.method = "post";
form.action = "http://localhost:8888/";
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.type = "hidden";
hiddenField.name = key;
hiddenField.value = params[key];
console.log(hiddenField);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
};
</script>
現在,我正在使用React,因為我想監聽所有按鍵並將返回的數據呈現到網頁上而無需刷新。 我有一個看起來像這樣的組件
class myComponent extends React.Component {
constructor() {
super();
this.state = {
x: null,
y: null,
z: null
};
}
componentDidMount() {
fetch("/some-endpoint")
.then(res => res.json())
.then(
returnData => this.setState(returnData),
() => console.log("State has been set to the return data")
);
}
render() {
return (
<div>
<h1>{this.state.x}</h1>
<h2>{this.state.y}</h2>
<h2>{this.state.z}</h2>
</div>
);
}
}
我想要做的基本上是讓我在HTML片段中運行的腳本在該組件中的某個位置上運行,但是我無法簡單地將其復制粘貼到div中的script標記中,並將其與HTML一起返回我在說“')'期望之類的內容時出錯,我真的不確定在這種情況下它們的含義。 我覺得我可能會采用錯誤的方式,但是基本上,我希望能夠使用React將功能添加到我的網頁中。 我認為它必須與myComponent
處於同一組件中才能告訴該組件更新其狀態,但是我對此可能是錯誤的。 如果有人可以指出正確的道路或給我一些指導,那將非常有幫助。 提前致謝!
聽起來您正在嘗試添加script
標簽以進行渲染,您只需將script
標簽內的代碼添加到componentDidMount
:
componentDidMount() {
document.onkeypress = evt => {
...
};
fetch("/some-endpoint")
.then(res => res.json())
.then(
returnData => this.setState(returnData,
() => console.log("State has been set to the return data")
));
}
另外,我注意到您的括號放在錯誤的位置,這可能是您看到錯誤的原因。 看到第二個.then
上面的,你應該將來自右括號returnData
在后setState
回調。
在反應過來,你要添加的事件監聽器里componentDidMount
並破壞內部的聽眾componentWillUnmount
。
您還想將處理程序移到類中的單獨函數中,以在破壞偵聽器時進行引用。
它看起來應該像這樣:
class myComponent extends React.Component {
...
componentDidMount() {
document.addEventListener('keypress', this.handleKeyPress.bind(this))
}
componentWillUnmount() {
document.removeEventListener('keypress', this.handleKeyPress)
}
handleKeyPress() {
fetch('/some-endpoint', { method: 'POST' })
.then(resp => resp.json())
.then(respJson => this.setState(respJson))
}
}
需要注意的一件事是,在您的代碼段中,用於處理提取響應的語法無效。
一個有用的資源是React網站上的以下文檔頁面:
https://react-cn.github.io/react/tips/dom-event-listeners.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.