首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Blueprintjs Toast组件的惯用反应

Blueprintjs Toast组件的惯用反应
EN

Stack Overflow用户
提问于 2016-11-27 04:08:12
回答 2查看 1.7K关注 0票数 2

Blueprint库提供了一个烤面包机组件,该组件显示用户操作的通知。从文档中,它被第一次调用使用

const MyToaster = Toaster.create({options}),然后是

MyToaster.show({message: 'some message'})

我很难将show方法融入React的生命周期--如何创建一个可重用的烤面包机组件,在不同的按钮单击时显示不同的消息?如果有帮助,我将使用MobX作为数据存储。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-06 01:17:35

在这方面,Toaster很有趣,因为它不关心您的反应生命周期。这意味着,它是必要的使用,以发出祝酒词,立即响应事件。

只需在相关事件处理程序中调用toaster.show() (无论是DOM单击还是Redux操作)。

看看我们是如何在示例本身中这样做的:toastExample.tsx

票数 1
EN

Stack Overflow用户

发布于 2017-02-02 09:24:57

我的解决方案与Redux (和redux-actions)..。

行动:

export const setToaster = createAction('SET_TOASTER');

减速器:

代码语言:javascript
复制
const initialState = {
  toaster: {
    message: ''
  }
};

function reducer(state = initialState, action) {
  switch(action.type) {
    case 'SET_TOASTER':
      return {
        ...state, 
        toaster: { ...state.toaster, ...action.payload }
      };
  };
}

烤面包机组件:

代码语言:javascript
复制
// not showing imports here...

class MyToaster extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // set default toaster props here like intent, position, etc.
      // or pass them in as props from redux state
      message: '',
      show: false
    };
  }

  componentDidMount() {
    this.toaster = Toaster.create(this.state);
  }

  componentWillReceiveProps(nextProps) {
    // if we receive a new message prop 
    // and the toaster isn't visible then show it
    if (nextProps.message && !this.state.show) {
      this.setState({ show: true });
    }
  }

  componentDidUpdate() {
    if (this.state.show) {
      this.showToaster();
    }
  }

  resetToaster = () => {
    this.setState({ show: false });

    // call redux action to set message to empty
    this.props.setToaster({ message: '' });
  }

  showToaster = () => {
    const options = { ...this.state, ...this.props };

    if (this.toaster) {
      this.resetToaster();
      this.toaster.show(options);
    }
  }

  render() {
    // this component never renders anything
    return null;
  }
}

应用程序组件:

或者不管你的根级成分是什么..。

代码语言:javascript
复制
const App = (props) =>
  <div>
    <MyToaster {...props.toaster} setToaster={props.actions.setToaster} />
  </div>

一些其他组件:

你需要调用烤面包机..。

代码语言:javascript
复制
class MyOtherComponent extends Component {
  handleSomething = () => {
    // We need to show a toaster!
    this.props.actions.setToaster({
      message: 'Hello World!'
    });
  }

  render() { ... }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40825668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档