【发布时间】:2019-09-27 13:06:39
【问题描述】:
我有一个功能组件,我想使用一个 onClick 来为一个简单的类似按钮调度一个动作。我使用 onClick 函数获取它所引用的 DOM 元素的存储属性,以更新它旨在影响的存储切片。
我尝试将数据作为道具传递,但无济于事。我也尝试过使用 react Ref,但这似乎是为类组件保留的
处理点击的组件
点赞和内容通过父组件的 props 从 Redux 存储中传递下来
import React from 'react';
import styles from '../scss/styles.scss';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {onNewLike} from './../actions';
function Post(props){
function doALike() {
const { dispatch } = props
dispatch(onNewLike())
}
return(
<div className="post">
<h1>{props.content}</h1>
<div className="post-statistics">
<p onClick={doALike}>LIKE</p>
<p>likes: {props.likes}</p>
</div>
</div>
);
}
Post.propTypes = {
content: PropTypes.string,
likes: PropTypes.number,
dispatch: PropTypes.func
}
export default connect()(Post)
我试图将帖子传递给的 Reducer,以便我可以更新每个独特帖子的点赞(尚未编写处理点赞的逻辑 - 只是想确保我得到每个帖子的点赞喜欢
import { initialState } from '../constants/initialState';
import c from './../constants';
export function likeReducer(state = initialState, action){
switch (action.type){
case c.NEW_LIKE:
console.log(action.id)
default:
return state;
}
}
允许用户生成新帖子并将“likes”设置为“0”的组件传递给 redux 商店
import React from 'react';
import styles from '../scss/styles.scss';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import {connect} from 'react-redux';
import {onNewPost} from './../actions';
function NewPost({dispatch}){
let _content = null;
function handleNewPost(e){
e.preventDefault();
let post = {content: _content.value, likes: 69, id: v4()}
dispatch(onNewPost(post))
}
return(
<div className='newPost'>
<h1>Create a Post</h1>
<form onSubmit={handleNewPost}>
<input type='text'
id='content'
className='newPostInput'
placeholder='Whats on your mind?'
ref={(input) => {_content = input;}}/>
<button type='submit'>Submit</button>
</form>
</div>
);
}
【问题讨论】:
标签: reactjs react-redux