首页 > 解决方案 > 如何将类组件中的道具发送到功能组件?

问题描述

我是 reactjs 的初学者。需要知道如何将一个页面中的道具值发送到另一个页面。道具在第一页我可以获取类组件值如何获取另一个页面中的值。提前致谢

墙色.jsx

import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}

另一个页面是 wall-factory-3d.js

import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}

我试过这个但没有得到输出。

标签: javascriptreactjsreact-redux

解决方案


意见,但这是我会做到的...... :)

this.state = {
 background: 'color',
 pickedWall: false,
}

const handleChangeComplete = (e) => {
 this.setState(prevState => ({
  ...prevState,
  pickedWall: true,
  background: e.target.value,
 }))
}

render() {
 const { x, y } = this.props     
 const { background, pickedWall } = this.state
 const { handleChangeComplete } = this

 return <SketchPicker {...{ x, y, background, handleChangeComplete, pickedWall }} />
}

在你的组件中......

const SketchPicker = ({
 x,
 y,
 background,
 pickedWall,
 handleChangeComplete,
}) => {
 return (
  <div>
   <SomeDiv onClick={(e) => handleChangeComplete(e)}>
    ...your code
   </SomeDiv>
   <Fragment>
    {pickedWall && <WallPicker {...{ x, y, background }} />}
   </Fragment>
  </div>
 )
}

推荐阅读