我有一个功能组件,我想使用onClick来为简单的“喜欢”按钮调度操作。我的onClick函数接受它所引用的DOM元素的商店属性,以便更新其设计要影响的商店切片。
我试图将数据作为道具传递,但无济于事。我也尝试过使用react Ref,但这似乎是为类组件保留的
处理点击的组件
喜欢和内容通过父组件中的道具从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;
}
}
该组件允许用户生成新帖子,并将设置为“ 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>
);
}
答案 0 :(得分:0)
您可以将所需的内容传递给doALike
函数,然后在点击处理程序中将其作为匿名函数进行调用,如下所示。
function Post(props){
function doALike(whateverProps) {
dispatch(onNewLike())
}
return(
<div className="post">
<h1>{props.content}</h1>
<div className="post-statistics">
<p onClick={() => {doALike(props)}}>LIKE</p>
<p>likes: {props.likes}</p>
</div>
</div>
);
}