反应:无法读取 null 的属性'innerText'



我正在尝试创建格式化输入文本的功能,但是,应用程序崩溃了,我收到了两个错误。每当我尝试键入任何一个表单字段时,我都会收到这个错误:Cannot read property 'innerText' of null,当我单击格式按钮时,我会得到这个错误Cannot read property 'innerHTML' of null。我正在使用React.js.

GitHub:https://github.com/Rahni1/mern_blog

如何解决这些错误?

谢谢!

class CreatePost extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "",
body: "",
createdPost: "",
error: "",
underlined: false,
};
this.onUnderlineClick = this.onUnderlineClick.bind(this);
}
onUnderlineClick(event) {
event.target.setAttribute(
"class",
!this.state.underlined ? "Selected" : ""
);
if (!this.state.underlined) {
this.outputRef.current.innerHTML += "<u></u>";
}
this.setState({
underlined: !this.state.underlined,
});
this.inputRef.current.focus();
}

formatText(text) {
switch (true) {
...
case this.state.underlined:
const allUnderlined = this.outputRef.current.getElementsByTagName("u");
const lastUnderlined = allUnderlined[allUnderlined.length - 1];
lastUnderlined.innerText += text;
break;
default:
this.outputRef.current.innerHTML += text;
break;
}
}
transferText() {
const input = this.inputRef.current.value;
const output = this.outputRef.current.innerHTML;
let inputCounter = input.length - 1,
outputCounter = output.length - 1,
isTag = false;
while (outputCounter > -1) {
if (output[outputCounter] === ">") {
isTag = true;
outputCounter -= 1;
continue;
}
if (isTag) {
isTag = output[outputCounter] !== "<";
outputCounter -= 1;
continue;
}
if (inputCounter <= -1) {
this.outputRef.current.innerHTML = this.outputRef.current.innerHTML.slice(
outputCounter + 1
);
break;
}
else {
let temp = this.outputRef.current.innerHTML;
temp =
temp.slice(0, outputCounter) +
input[inputCounter] +
temp.slice(outputCounter + 1);
this.outputRef.current.innerHTML = temp;
inputCounter -= 1;
outputCounter -= 1;
}
}
}
changeHandler = (e) => {
const input = this.inputRef.current.value;
const output = this.outputRef.current.innerText;
if (input.length > output.length) {
const newText = input.slice(output.length);
this.formatText(newText);
} else {
this.transferText();
}
this.setState({ [e.target.name]: e.target.value });
};
... 
render() {
const { title, body } = this.state;
return (
<>
<div>     
<form onSubmit={this.submitHandler}>
<div className="form-group">
<input
type="text"
name="title"
onChange={this.changeHandler}
value={title}
/>
</div>
<span>
<button
type="button"
onClick={this.onUnderlineClick}>
<u>U</u>
</button>
</span>
<div>
<textarea
ref={this.inputRef}
className="Text"
onChange={this.changeHandler}
value={body}
/>
</div>
...
</form>
</div>
<div ref={this.outputRef}></div>
</div>
</>
);
}
}

尝试使用

innerRef={r=>this.inputRef=r}

而不是

ref={this.inputRef}

首先,您必须更新ref属性:

ref={node => this.node = node}

更新后changeHandler

changeHandler = (e) => {
const input = this.inputRef.value;
...

并在所有使用ref 的地方进行类似的更改

最新更新