【发布时间】:2020-08-26 20:33:20
【问题描述】:
TLDR
我正在为我的项目制作一个多步骤表单,其灵感来自Brad Traversy's Tutorial of making Multi-Step form in React。
所以按照这个表格的基本结构
我制作了一个名为Multiform 的主要父组件,如下所示
import React, { Component } from 'react'
import StepOne from './StepOne'
export class Multiform extends Component {
state = {
step:1,
CountryFlag: 'https://raw.githubusercontent.com/MeRahulAhire/country-calling-code-html/master/phone_icon.png',
CountryCode: ''
};
handleChange = (input) => (e) => {
this.setState({ [input]: e.target.value });
};
countryFlagHandler = () =>{
this.setState({CountryFlag : this.props.state.flagImg})
}
render() {
const { CountryFlag, CountryCode } = this.state;
const values = {CountryFlag, CountryCode };
switch (step) {
case 1:
return(
<StepOne
handleChange={this.handleChange}
countryFlagHandler={this.countryFlagHandler}
values={values}
/>
)
default:
return (<h1>hello React App</h1>)
};
}
}
export default Multiform
还有一个子组件StepOne如下
import React, { Component } from 'react'
export class StepOne extends Component {
state = {
flagImg: '',
};
render() {
const { values, handleChange, countryFlagHandler } = this.props;
const selectCountryChange = () => {
const img = document.querySelector('#img');
const select = document.querySelector('#country');
img.src = `https://flagpedia.net/data/flags/h80/${select.selectedOptions[0].dataset.countrycode.toLowerCase()}.webp`;
this.setState({
flagImg: `https://flagpedia.net/data/flags/h80/${select.selectedOptions[0].dataset.countrycode.toLowerCase()}.webp`
});
countryFlagHandler()
};
return (
<div>
<div class="image" onChange={selectCountryChange}>
<img src={values.CountryFlag} id="img"/>
</div>
<select id="country" onChange={handleChange('select')} defaultValue={values.select}>
<option data-countryCode="IN" value="91">India</option>
<option data-countryCode="US" value="1">US</option>
<option data-countryCode="GB" value="44">UK</option>
</select>
</div>
)
}
}
export default StepOne
我要做的实际上是将<Select/> 和<img> 的数据同步并保留在Multiform.js 组件中,就像我们在步进表单中看到的那样。
但是,就像StepOne
<img src={values.CountryFlag} id="img"/>
img.src 实际上是由函数selectCountryChange 操作的,为了保持img.src 的值不变,我想在Multiform 中创建countryFlagHandler 并将其导入StepOne
但是当我选择任何值时,它给了我这个错误:
TypeError:无法读取未定义的属性“flagImg”
Registration.countryFlagHandler
C:/Users/Rahul/Desktop/cfm-usersignup/src/public/form/registration.js:53
50 | this.setState({ [input]: e.target.value });
51 | };
52 | countryFlagHandler = () =>{
> 53 | this.setState({CountryFlag : this.props.state.flagImg})
| ^ 54 | }
55 |
56 |
&
selectCountryChange
C:/Users/Rahul/Desktop/cfm-usersignup/src/public/form/credential.js:31
28 | this.setState({
29 | flagImg: `https://flagpedia.net/data/flags/h80/${select.selectedOptions[0].dataset.countrycode.toLowerCase()}.webp`
30 | });
> 31 | countryFlagHandler();
| ^ 32 | };
33 | return (
34 | <div>
谁能告诉我如何纠正我的错误?
【问题讨论】:
标签: reactjs default-value react-props setstate react-state-management