이것은 약간의 longwinded 문제이며 해결할 두통의 톤을 제공합니다.여러 양식을 렌더링하는 구성 요소에서 상태를 사용하지 않고 onSubmit 양식에 입력 값을 전달하는 방법은 무엇입니까?
투표 앱을 만들고 있습니다. 이 페이지에는 투표 할 수있는 투표 목록이 있습니다. 각 폴링은 해당 폴링에 사용할 수있는 여러 옵션을 나타내는 입력 라디오 단추로 구성된 양식입니다.
이전에 내가 수행 한 작업은 구성 요소 상태로 선택한 옵션을 this.state.value
에 저장 한 다음 양식을 제출할 때 작업 작성자에게 인수로 전달하는 것이 었습니다.
하나의 설문 조사 옵션을 클릭하고 다른 설문 조사에서 제출을 클릭하면 실제로 잘못된 설문 조사에 잘못된 옵션을 제출했습니다.
입력 값을 구성 요소 상태로 저장하지 않고 onSubmit
양식을 전달하는 방법이 있습니까?
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import Loading from '../Loading';
class MyPolls extends Component {
constructor(props) {
super(props);
this.state = {
skip: 0,
isLoading: true,
isLoadingMore: false,
value: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.props.fetchMyPolls(this.state.skip)
.then(() => {
setTimeout(() => {
this.setState({
skip: this.state.skip + 4,
isLoading: false
});
}, 1000);
});
}
sumVotes(acc, cur) {
return acc.votes + cur.votes
}
loadMore(skip) {
this.setState({ isLoadingMore: true });
setTimeout(() => {
this.props.fetchMyPolls(skip)
.then(() => {
const nextSkip = this.state.skip + 4;
this.setState({
skip: nextSkip,
isLoadingMore: false
});
});
}, 1000);
}
handleSubmit(title, e) {
// console.log(e.target);
e.preventDefault();
const vote = {
title,
option: this.state.value
};
console.log(vote)
}
handleChange(event) {
this.setState({ value: event.target.value });
}
renderPolls() {
return this.props.polls.map(poll => {
return (
<div
className='card'
key={poll._id}
style={{ width: '350px', height: '400px' }}>
<div className='card-content'>
<span className='card-title'>{poll.title}</span>
<p>
Total votes: {poll.options.reduce((acc, cur) => { return acc + cur.votes }, 0)}
</p>
<form onSubmit={e => this.handleSubmit(poll.title, e)}>
{poll.options.map(option => {
return (
<p key={option._id}>
<input
name={poll.title}
className='with-gap'
type='radio'
id={option._id}
value={option.option}
onChange={this.handleChange}
/>
<label htmlFor={option._id}>
{option.option}
</label>
</p>
)
})}
<button
type='text'
className='activator teal btn waves-effect waves-light'
style={{
position: 'absolute',
bottom: '10%',
transform: 'translateX(-50%)'
}}
>
Submit
<i className='material-icons right'>
send
</i>
</button>
</form>
</div>
<div className='card-reveal'>
<span className='card-title'>{poll.title}
<i className='material-icons right'>close</i>
</span>
<p>
dsfasfasdf
</p>
</div>
</div>
)
})
}
render() {
return (
<div className='center-align container'>
<h2>My Polls</h2>
{this.state.isLoading ? <Loading size='big' /> :
<div
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
alignItems: 'center',
alignContent: 'center'
}}>
{this.renderPolls()}
</div>}
<div className='row'>
{this.state.isLoadingMore ? <Loading size='small' /> :
<button
className='btn red lighten-2 wave-effect waves-light' onClick={() => this.loadMore(this.state.skip)}>
Load More
</button>}
</div>
</div>
);
}
}
function mapStateToProps({ polls }) {
return { polls }
}
export default connect(mapStateToProps, actions)(MyPolls);
앱 데모 : https://voting-app-drhectapus.herokuapp.com/ (사용 [email protected]
과 암호 123
로그인하기)
Github에서의 환매 특약 : https://github.com/drhectapus/voting-app
내가 어떤 제안에 개방적이야. 감사!
문제에 대한 일반적인 솔루션은 독립적 인'state'와 함께 (A' '구성 요소 클래스를 생성하는 것' onSubmit()')을 호출하여 각'Poll'을 렌더링합니다. –
내가 간과했던 쉬운 해결책이 있다는 것을 알았습니다. 감사 ! – doctopus