tsx 编写react 遇见类型“Readonly<{}>”上不存在属性XXX解决办法
<p>这样的问题是TS语法类型检测的时候会报错,这时候可以给state个props生命类型,问题解决,代码如下:</p><div class="cnblogs_code">
<pre>import React from "react"<span style="color: rgba(0, 0, 0, 1)">;
type StateType </span>=<span style="color: rgba(0, 0, 0, 1)"> {
name: string;
number: number;
};
type propType </span>=<span style="color: rgba(0, 0, 0, 1)"> {
name: string;
number: number;
};
interface Test1 {
state: StateType;
props:propType
}
class Test1 extends React.Component {
constructor(props) {
super(props);
</span><span style="color: rgba(0, 0, 255, 1)">this</span>.state =<span style="color: rgba(0, 0, 0, 1)"> {
name: </span>""<span style="color: rgba(0, 0, 0, 1)">,
number: </span>2<span style="color: rgba(0, 0, 0, 1)">
};
}
render() {
console.log(</span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.props.name);
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> (
</span><div>
<div>
<label htmlFor="">单号</label>
<<span style="color: rgba(0, 0, 0, 1)">input
type</span>="text"<span style="color: rgba(0, 0, 0, 1)">
value</span>={<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.state.name}
onChange</span>={e => <span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.setState({ name: e.target.value })}
</span>/>
</div>
<div>
<label htmlFor="">创建用户</label>
<<span style="color: rgba(0, 0, 0, 1)">input
type</span>="text"<span style="color: rgba(0, 0, 0, 1)">
value</span>={<span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.state.number}
onChange</span>={e => <span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.setState({ number: e.target.value })}
</span>/>
</div>
<div></div>
</div>
<span style="color: rgba(0, 0, 0, 1)"> );
}
}
export </span><span style="color: rgba(0, 0, 255, 1)">default</span> Test1;</pre>
</div>
<p>这个</p>
<pre><span>propType和<br></span></pre>
<pre><span>StateType </span><br>就是声明类型的地方,如此问题解决,网上还有一种方案是把</pre>
<pre>React.Component改成</pre>
<pre> React.Component<any, any><br>但是这样一来对state和props的类型检测就失去意义了,所以不太建议使用<br>但是其实还能这么写,看一下TS的解释会发现</pre>
<pre>React.Component<any, any></pre>
<pre><span> 这里面的第一个any可以是props的类型,第二个any可以是state的类型,即:<br></span></pre>
<div>class Test1 extends React.Component<propType,StateType></div>
<div>问题一样可以解决</div>
<pre><span> </span></pre>
</div>
<div id="MySignature" role="contentinfo">
积累小的知识,才能成就大的智慧,希望网上少一些复制多一些原创有用的答案<br><br>
来源:https://www.cnblogs.com/llcdbk/p/13029996.html
頁:
[1]