我有一个表,该表具有名称和json条目作为列。我想使用ReactJS制作一个使用JSON格式的字符串名称和JSON条目名称的表单,并将其发布到Phoenix API。
PS:我是ReactJS的新手。抱歉,很傻。
interface Mystate
{
asset_meta_label: string;
asset_meta_attribute: JSON;
}
export default class Form extends React.Component<{}, Mystate> {
constructor(props: {}) {
super(props);
this.state = {
asset_meta_label: '',
asset_meta_attribute: {} //Error: Type '{}' is missing the following properties from type 'JSON': parse, stringify
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit (event)
{
event.preventDefault();
fetch('/api/create', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
asset_class_meta:
{
asset_meta_label: this.state.asset_meta_label,
asset_meta_attribute: this.state.asset_meta_attribute
}
})
})
}
handleAssetClassMeta(event) {
this.setState({ asset_meta_label: event.target.value })
}
handleAssetMetaAttribute(event) {
this.setState({ asset_meta_attribute: event.target.value })
}
public render(): JSX.Element {
return (
<Main>
<h1>Add Asset Details</h1>
<form onSubmit={this.handleSubmit}>
<div className="field">
<label className="label">Asset Class</label>
<div className="control">
<input
className="input"
type="text"
placeholder="Enter Asset Id"
value = {this.state.asset_meta_label}
onChange = {this.handleAssetClassMeta.bind(this)}
/>
</div>
</div>
<br />
<div className="field">
<label className="label">Asset Class Attributes</label>
<div className="control">
<input
className="input"
type={JSON} //Error: Type 'JSON' is not assignable to type 'string'
placeholder="Enter Asset Class"
value = {this.state.asset_meta_attribute} //Type 'JSON' is not assignable to type 'string | number | string[] | undefined'.
onChange = {this.handleAssetMetaAttribute.bind(this)}
/>
</div>
</div>
<br />
<br />
<button
type="submit"
value="Submit"
className="button is-primary">
Submit
</button>
</form>
<button>
<Link to="/">Back to home</Link>
</button>
</Main>
);
}
}
错误1:类型“ {}”缺少类型“ JSON”中的以下属性:解析,字符串化 错误2:类型“ JSON”不能分配给类型“字符串”
答案 0 :(得分:1)
错误1:
我想您希望asset_meta_attribute是一个对象。您有三个选择
asset_meta_attribute: any;
export default class Form extends React.Component {
(我建议您不要使用此选项)错误2:
输入元素类型定义为字符串。有关可能的类型,请检查以下链接:
https://www.w3schools.com/tags/att_input_type.asp
答案 1 :(得分:1)
如果用户必须在文本字段中输入JSON,则可能需要将其定义为字符串,然后进行解析:
id movie cast genres runtime
0 1 Furious a/b/c/d a/b// 23
1 2 Minions a/b/c/ a/b/c/ 55
2 3 Mission a/b// a/// 67
3 4 Kingsman a/b/c/d a/b/c/d 23
4 5 Star_Wars a/// a/b/c/ 45