我有多个父组件,所有形式,它是一个检查生成器。您输入您的信息,他们会为您打印支票。子组件是检查布局,其中所有数据都来自表单。这是我的第一个父组件 - BusinessAddressimport React from 'react';import './../App.css';import Check from './Check';class BusinessAddress extends React.Component { constructor(props) { super(props); this.state = {text: { name: 'BusinessAddress', a: '', b: '', c: '', d: '', e: '', f: '', g: '', h: '' }}; } handleChange(property, event) { console.log(event.target.value); const text = {...this.state.text}; text[property] = event.target.value; this.setState({text: text}); } handleSubmit(event) { console.log(this.state.text.e); } render() { return ( <div> <div className="form-box"> <h3>Business Address</h3> <label>Business Name</label> <input type="text" placeholder="Business Name" value={this.state.text.a} onChange={this.handleChange.bind(this, 'a')} maxLength="30" /> <label>Name Line 2</label> <input type="text" placeholder="Business Name Line 2" value={this.state.text.b} onChange={this.handleChange.bind(this, 'b')} maxLength="90" /> <label>Street Address</label> <input type="text" placeholder="Street Address" value={this.state.text.c} onChange={this.handleChange.bind(this, 'c')} maxLength="30" /> <label>Address Line 2</label> <input type="text" placeholder="Street Address Line 2" value={this.state.text.d} onChange={this.handleChange.bind(this, 'd')} maxLength="30" /> <label>City</label> <input type="text" className="short" placeholder="City" value={this.state.text.e} onChange={this.handleChange.bind(this, 'e')} maxLength="30" /> <label>State</label> </div> ) }}在子组件中,我希望能够根据其父组件找出数据来自哪个组件以及将其放置在 DOM 中的何处。您可以在我的父组件中BusinessAddress看到我已将组件的名称添加到状态以传递给子组件。我只是不确定如何处理 IF 语句,或者我是否以正确的方式传递数据。
2 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
您可以循环思考您的键而不是循环您的值,这将允许您使用key作为字段的名称,然后您可以使用该键获取值,例如:
render() {
const newObject = this.props.data;
const data = Object.keys(newObject);
return (
<div>
{
data.map(key => {
if(key === 'b') {
return <div> Business Name Line 2: {data[key]} </div>
} else if(key === 'c') {
return <div> Street Address: {data[key]} </div>
}
})
}
</div>
)
}
添加回答
举报
0/150
提交
取消